{"version":3,"file":"maplibre-gl-csp.js","sources":["../node_modules/tslib/tslib.es6.js","../node_modules/@mapbox/point-geometry/index.js","../node_modules/@mapbox/unitbezier/index.js","../src/util/offscreen_canvas_supported.ts","../src/util/offscreen_canvas_distorted.ts","../src/util/util.ts","../src/util/abort_error.ts","../src/util/browser.ts","../src/util/dom.ts","../src/util/config.ts","../src/source/protocol_crud.ts","../src/util/ajax.ts","../src/util/webp_supported.ts","../src/util/image_request.ts","../src/util/request_manager.ts","../src/util/evented.ts","../node_modules/@maplibre/maplibre-gl-style-spec/dist/index.mjs","../src/style/validate_style.ts","../src/util/transferable_grid_index.ts","../src/util/web_worker_transfer.ts","../src/style/zoom_history.ts","../src/util/is_char_in_unicode_block.ts","../src/util/script_detection.ts","../src/source/rtl_text_plugin_worker.ts","../src/style/evaluation_parameters.ts","../src/style/properties.ts","../src/style/style_layer.ts","../src/util/struct_array.ts","../src/data/array_types.g.ts","../src/data/bucket/circle_attributes.ts","../src/data/segment.ts","../src/shaders/encode_attribute.ts","../src/data/bucket/pattern_attributes.ts","../node_modules/murmurhash-js/murmurhash3_gc.js","../node_modules/murmurhash-js/murmurhash2_gc.js","../node_modules/murmurhash-js/index.js","../src/data/feature_position_map.ts","../src/render/uniform_binding.ts","../src/data/program_configuration.ts","../src/data/extent.ts","../src/data/load_geometry.ts","../src/data/evaluation_feature.ts","../src/data/bucket/circle_bucket.ts","../src/util/intersection_tests.ts","../src/style/query_utils.ts","../src/style/style_layer/circle_style_layer_properties.g.ts","../node_modules/gl-matrix/esm/common.js","../node_modules/gl-matrix/esm/mat4.js","../node_modules/gl-matrix/esm/vec3.js","../node_modules/gl-matrix/esm/vec4.js","../node_modules/gl-matrix/esm/vec2.js","../src/style/style_layer/circle_style_layer.ts","../src/data/bucket/heatmap_bucket.ts","../src/style/style_layer/heatmap_style_layer_properties.g.ts","../src/util/image.ts","../src/util/color_ramp.ts","../src/style/style_layer/heatmap_style_layer.ts","../src/style/style_layer/hillshade_style_layer_properties.g.ts","../src/style/style_layer/hillshade_style_layer.ts","../src/data/bucket/fill_attributes.ts","../node_modules/earcut/src/earcut.js","../src/data/bucket/pattern_bucket_features.ts","../src/data/bucket/fill_bucket.ts","../src/style/style_layer/fill_style_layer_properties.g.ts","../src/style/style_layer/fill_style_layer.ts","../src/data/bucket/fill_extrusion_attributes.ts","../node_modules/@mapbox/vector-tile/lib/vectortilefeature.js","../node_modules/@mapbox/vector-tile/lib/vectortilelayer.js","../node_modules/@mapbox/vector-tile/lib/vectortile.js","../node_modules/@mapbox/vector-tile/index.js","../src/data/bucket/fill_extrusion_bucket.ts","../src/style/style_layer/fill_extrusion_style_layer_properties.g.ts","../src/style/style_layer/fill_extrusion_style_layer.ts","../src/data/bucket/line_attributes.ts","../src/data/bucket/line_attributes_ext.ts","../src/data/bucket/line_bucket.ts","../src/style/style_layer/line_style_layer_properties.g.ts","../src/style/style_layer/line_style_layer.ts","../src/data/bucket/symbol_attributes.ts","../src/symbol/transform_text.ts","../src/util/verticalize_punctuation.ts","../src/symbol/one_em.ts","../node_modules/pbf/index.js","../node_modules/ieee754/index.js","../src/style/parse_glyph_pbf.ts","../node_modules/potpack/index.js","../src/render/image_atlas.ts","../src/symbol/shaping.ts","../src/symbol/symbol_size.ts","../src/style/style_layer/overlap_mode.ts","../src/data/bucket/symbol_bucket.ts","../src/symbol/merge_lines.ts","../src/style/style_layer/symbol_style_layer_properties.g.ts","../src/style/format_section_override.ts","../src/style/style_layer/symbol_style_layer.ts","../src/util/resolve_tokens.ts","../src/style/style_layer/background_style_layer_properties.g.ts","../src/style/style_layer/background_style_layer.ts","../src/style/style_layer/raster_style_layer_properties.g.ts","../src/style/style_layer/raster_style_layer.ts","../src/style/style_layer/custom_style_layer.ts","../src/style/create_style_layer.ts","../src/util/style.ts","../src/style/load_sprite.ts","../src/render/texture.ts","../src/style/style_image.ts","../src/render/image_manager.ts","../node_modules/@mapbox/tiny-sdf/index.js","../src/render/glyph_manager.ts","../src/style/load_glyph_range.ts","../src/style/light.ts","../src/style/sky.ts","../src/render/line_atlas.ts","../src/util/throttled_invoker.ts","../src/util/actor.ts","../src/util/worker_pool.ts","../src/util/web_worker.ts","../src/util/global_worker_pool.ts","../src/util/dispatcher.ts","../src/source/query_features.ts","../src/source/load_tilejson.ts","../src/geo/lng_lat.ts","../src/geo/lng_lat_bounds.ts","../src/geo/mercator_coordinate.ts","../src/source/tile_bounds.ts","../src/source/vector_tile_source.ts","../src/source/raster_tile_source.ts","../node_modules/@mapbox/whoots-js/index.mjs","../src/source/tile_id.ts","../src/util/world_bounds.ts","../src/data/dem_data.ts","../src/source/raster_dem_tile_source.ts","../src/source/geojson_source.ts","../src/data/raster_bounds_attributes.ts","../src/source/image_source.ts","../src/source/video_source.ts","../src/source/canvas_source.ts","../src/source/source.ts","../src/util/dictionary_coder.ts","../src/util/vectortile_to_geojson.ts","../src/data/feature_index.ts","../src/source/rtl_text_plugin_status.ts","../src/source/rtl_text_plugin_main_thread.ts","../src/source/tile.ts","../src/data/bucket.ts","../src/source/tile_cache.ts","../src/source/source_state.ts","../src/source/source_cache.ts","../src/symbol/path_interpolator.ts","../src/symbol/grid_index.ts","../src/symbol/projection.ts","../src/symbol/collision_index.ts","../src/symbol/clip_line.ts","../src/symbol/anchor.ts","../src/style/style_layer/variable_text_anchor.ts","../src/source/pixels_to_tile_units.ts","../src/symbol/placement.ts","../src/symbol/symbol_layout.ts","../src/geo/projection/projection.ts","../src/style/pauseable_placement.ts","../node_modules/kdbush/index.js","../src/symbol/cross_tile_symbol_index.ts","../src/style/style.ts","../src/data/pos_attributes.ts","../src/shaders/shaders.ts","../src/shaders/_prelude.fragment.glsl.g.ts","../src/shaders/_prelude.vertex.glsl.g.ts","../src/shaders/background.fragment.glsl.g.ts","../src/shaders/background.vertex.glsl.g.ts","../src/shaders/background_pattern.fragment.glsl.g.ts","../src/shaders/background_pattern.vertex.glsl.g.ts","../src/shaders/circle.fragment.glsl.g.ts","../src/shaders/circle.vertex.glsl.g.ts","../src/shaders/clipping_mask.fragment.glsl.g.ts","../src/shaders/clipping_mask.vertex.glsl.g.ts","../src/shaders/heatmap.fragment.glsl.g.ts","../src/shaders/heatmap.vertex.glsl.g.ts","../src/shaders/heatmap_texture.fragment.glsl.g.ts","../src/shaders/heatmap_texture.vertex.glsl.g.ts","../src/shaders/collision_box.fragment.glsl.g.ts","../src/shaders/collision_box.vertex.glsl.g.ts","../src/shaders/collision_circle.fragment.glsl.g.ts","../src/shaders/collision_circle.vertex.glsl.g.ts","../src/shaders/debug.fragment.glsl.g.ts","../src/shaders/debug.vertex.glsl.g.ts","../src/shaders/fill.fragment.glsl.g.ts","../src/shaders/fill.vertex.glsl.g.ts","../src/shaders/fill_outline.fragment.glsl.g.ts","../src/shaders/fill_outline.vertex.glsl.g.ts","../src/shaders/fill_outline_pattern.fragment.glsl.g.ts","../src/shaders/fill_outline_pattern.vertex.glsl.g.ts","../src/shaders/fill_pattern.fragment.glsl.g.ts","../src/shaders/fill_pattern.vertex.glsl.g.ts","../src/shaders/fill_extrusion.fragment.glsl.g.ts","../src/shaders/fill_extrusion.vertex.glsl.g.ts","../src/shaders/fill_extrusion_pattern.fragment.glsl.g.ts","../src/shaders/fill_extrusion_pattern.vertex.glsl.g.ts","../src/shaders/hillshade_prepare.fragment.glsl.g.ts","../src/shaders/hillshade_prepare.vertex.glsl.g.ts","../src/shaders/hillshade.fragment.glsl.g.ts","../src/shaders/hillshade.vertex.glsl.g.ts","../src/shaders/line.fragment.glsl.g.ts","../src/shaders/line.vertex.glsl.g.ts","../src/shaders/line_gradient.fragment.glsl.g.ts","../src/shaders/line_gradient.vertex.glsl.g.ts","../src/shaders/line_pattern.fragment.glsl.g.ts","../src/shaders/line_pattern.vertex.glsl.g.ts","../src/shaders/line_sdf.fragment.glsl.g.ts","../src/shaders/line_sdf.vertex.glsl.g.ts","../src/shaders/raster.fragment.glsl.g.ts","../src/shaders/raster.vertex.glsl.g.ts","../src/shaders/symbol_icon.fragment.glsl.g.ts","../src/shaders/symbol_icon.vertex.glsl.g.ts","../src/shaders/symbol_sdf.fragment.glsl.g.ts","../src/shaders/symbol_sdf.vertex.glsl.g.ts","../src/shaders/symbol_text_and_icon.fragment.glsl.g.ts","../src/shaders/symbol_text_and_icon.vertex.glsl.g.ts","../src/shaders/terrain.fragment.glsl.g.ts","../src/shaders/terrain.vertex.glsl.g.ts","../src/shaders/terrain_depth.fragment.glsl.g.ts","../src/shaders/terrain_depth.vertex.glsl.g.ts","../src/shaders/terrain_coords.fragment.glsl.g.ts","../src/shaders/terrain_coords.vertex.glsl.g.ts","../src/shaders/sky.fragment.glsl.g.ts","../src/shaders/sky.vertex.glsl.g.ts","../src/render/vertex_array_object.ts","../src/render/program/terrain_program.ts","../src/render/program.ts","../src/render/program/pattern.ts","../src/render/program/fill_extrusion_program.ts","../node_modules/gl-matrix/esm/mat3.js","../src/render/program/fill_program.ts","../src/render/program/circle_program.ts","../src/render/program/collision_program.ts","../src/render/program/debug_program.ts","../src/render/program/clipping_mask_program.ts","../src/render/program/heatmap_program.ts","../src/render/program/hillshade_program.ts","../src/render/program/line_program.ts","../src/render/program/raster_program.ts","../src/render/program/symbol_program.ts","../src/render/program/background_program.ts","../src/render/program/program_uniforms.ts","../src/render/program/sky_program.ts","../src/gl/index_buffer.ts","../src/gl/vertex_buffer.ts","../src/gl/webgl2.ts","../src/gl/value.ts","../src/gl/framebuffer.ts","../src/gl/color_mode.ts","../src/gl/context.ts","../src/gl/depth_mode.ts","../src/gl/stencil_mode.ts","../src/gl/cull_face_mode.ts","../src/render/draw_collision_debug.ts","../src/render/draw_symbol.ts","../src/render/draw_heatmap.ts","../src/render/update_pattern_positions_in_program.ts","../src/render/draw_fill.ts","../src/render/draw_fill_extrusion.ts","../src/render/draw_hillshade.ts","../src/render/draw_raster.ts","../src/render/draw_debug.ts","../src/render/draw_terrain.ts","../src/render/mesh.ts","../src/render/painter.ts","../src/render/draw_sky.ts","../src/render/draw_circle.ts","../src/render/draw_line.ts","../src/render/draw_background.ts","../src/render/draw_custom.ts","../src/util/primitives.ts","../src/geo/edge_insets.ts","../src/geo/transform.ts","../node_modules/gl-matrix/esm/mat2.js","../src/util/throttle.ts","../src/ui/hash.ts","../src/ui/handler_inertia.ts","../src/ui/events.ts","../src/ui/handler/map_event.ts","../src/ui/handler/transform-provider.ts","../src/ui/handler/box_zoom.ts","../src/ui/handler/handler_util.ts","../src/ui/handler/tap_recognizer.ts","../src/ui/handler/tap_zoom.ts","../src/ui/handler/drag_handler.ts","../src/ui/handler/drag_move_state_manager.ts","../src/ui/handler/mouse.ts","../src/ui/handler/touch_pan.ts","../src/ui/handler/two_fingers_touch.ts","../src/ui/handler/keyboard.ts","../src/ui/handler/scroll_zoom.ts","../src/ui/handler/shim/dblclick_zoom.ts","../src/ui/handler/click_zoom.ts","../src/ui/handler/tap_drag_zoom.ts","../src/ui/handler/shim/drag_pan.ts","../src/ui/handler/shim/drag_rotate.ts","../src/ui/handler/shim/two_fingers_touch.ts","../src/ui/handler/cooperative_gestures.ts","../src/ui/handler_manager.ts","../src/ui/camera.ts","../src/ui/control/attribution_control.ts","../src/ui/control/logo_control.ts","../src/util/task_queue.ts","../src/util/performance.ts","../src/data/pos3d_attributes.ts","../src/source/terrain_source_cache.ts","../src/render/terrain.ts","../src/gl/render_pool.ts","../src/render/render_to_texture.ts","../src/ui/default_locale.ts","../src/ui/map.ts","../src/ui/handler/one_finger_touch_drag.ts","../src/ui/control/navigation_control.ts","../src/util/geolocation_support.ts","../src/util/smart_wrap.ts","../src/ui/anchor.ts","../src/ui/marker.ts","../src/ui/control/geolocate_control.ts","../src/ui/control/scale_control.ts","../src/ui/popup.ts","../src/index.ts","../src/ui/control/fullscreen_control.ts","../src/ui/control/terrain_control.ts"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\r\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\r\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose, inner;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n if (async) inner = dispose;\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n var r, s = 0;\r\n function next() {\r\n while (r = env.stack.pop()) {\r\n try {\r\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\r\n if (r.dispose) {\r\n var result = r.dispose.call(r.value);\r\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n else s |= 1;\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","'use strict';\n\nmodule.exports = Point;\n\n/**\n * A standalone point geometry with useful accessor, comparison, and\n * modification methods.\n *\n * @class Point\n * @param {Number} x the x-coordinate. this could be longitude or screen\n * pixels, or any other sort of unit.\n * @param {Number} y the y-coordinate. this could be latitude or screen\n * pixels, or any other sort of unit.\n * @example\n * var point = new Point(-77, 38);\n */\nfunction Point(x, y) {\n this.x = x;\n this.y = y;\n}\n\nPoint.prototype = {\n\n /**\n * Clone this point, returning a new point that can be modified\n * without affecting the old one.\n * @return {Point} the clone\n */\n clone: function() { return new Point(this.x, this.y); },\n\n /**\n * Add this point's x & y coordinates to another point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n add: function(p) { return this.clone()._add(p); },\n\n /**\n * Subtract this point's x & y coordinates to from point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n sub: function(p) { return this.clone()._sub(p); },\n\n /**\n * Multiply this point's x & y coordinates by point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n multByPoint: function(p) { return this.clone()._multByPoint(p); },\n\n /**\n * Divide this point's x & y coordinates by point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n divByPoint: function(p) { return this.clone()._divByPoint(p); },\n\n /**\n * Multiply this point's x & y coordinates by a factor,\n * yielding a new point.\n * @param {Point} k factor\n * @return {Point} output point\n */\n mult: function(k) { return this.clone()._mult(k); },\n\n /**\n * Divide this point's x & y coordinates by a factor,\n * yielding a new point.\n * @param {Point} k factor\n * @return {Point} output point\n */\n div: function(k) { return this.clone()._div(k); },\n\n /**\n * Rotate this point around the 0, 0 origin by an angle a,\n * given in radians\n * @param {Number} a angle to rotate around, in radians\n * @return {Point} output point\n */\n rotate: function(a) { return this.clone()._rotate(a); },\n\n /**\n * Rotate this point around p point by an angle a,\n * given in radians\n * @param {Number} a angle to rotate around, in radians\n * @param {Point} p Point to rotate around\n * @return {Point} output point\n */\n rotateAround: function(a,p) { return this.clone()._rotateAround(a,p); },\n\n /**\n * Multiply this point by a 4x1 transformation matrix\n * @param {Array} m transformation matrix\n * @return {Point} output point\n */\n matMult: function(m) { return this.clone()._matMult(m); },\n\n /**\n * Calculate this point but as a unit vector from 0, 0, meaning\n * that the distance from the resulting point to the 0, 0\n * coordinate will be equal to 1 and the angle from the resulting\n * point to the 0, 0 coordinate will be the same as before.\n * @return {Point} unit vector point\n */\n unit: function() { return this.clone()._unit(); },\n\n /**\n * Compute a perpendicular point, where the new y coordinate\n * is the old x coordinate and the new x coordinate is the old y\n * coordinate multiplied by -1\n * @return {Point} perpendicular point\n */\n perp: function() { return this.clone()._perp(); },\n\n /**\n * Return a version of this point with the x & y coordinates\n * rounded to integers.\n * @return {Point} rounded point\n */\n round: function() { return this.clone()._round(); },\n\n /**\n * Return the magitude of this point: this is the Euclidean\n * distance from the 0, 0 coordinate to this point's x and y\n * coordinates.\n * @return {Number} magnitude\n */\n mag: function() {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n },\n\n /**\n * Judge whether this point is equal to another point, returning\n * true or false.\n * @param {Point} other the other point\n * @return {boolean} whether the points are equal\n */\n equals: function(other) {\n return this.x === other.x &&\n this.y === other.y;\n },\n\n /**\n * Calculate the distance from this point to another point\n * @param {Point} p the other point\n * @return {Number} distance\n */\n dist: function(p) {\n return Math.sqrt(this.distSqr(p));\n },\n\n /**\n * Calculate the distance from this point to another point,\n * without the square root step. Useful if you're comparing\n * relative distances.\n * @param {Point} p the other point\n * @return {Number} distance\n */\n distSqr: function(p) {\n var dx = p.x - this.x,\n dy = p.y - this.y;\n return dx * dx + dy * dy;\n },\n\n /**\n * Get the angle from the 0, 0 coordinate to this point, in radians\n * coordinates.\n * @return {Number} angle\n */\n angle: function() {\n return Math.atan2(this.y, this.x);\n },\n\n /**\n * Get the angle from this point to another point, in radians\n * @param {Point} b the other point\n * @return {Number} angle\n */\n angleTo: function(b) {\n return Math.atan2(this.y - b.y, this.x - b.x);\n },\n\n /**\n * Get the angle between this point and another point, in radians\n * @param {Point} b the other point\n * @return {Number} angle\n */\n angleWith: function(b) {\n return this.angleWithSep(b.x, b.y);\n },\n\n /*\n * Find the angle of the two vectors, solving the formula for\n * the cross product a x b = |a||b|sin(θ) for θ.\n * @param {Number} x the x-coordinate\n * @param {Number} y the y-coordinate\n * @return {Number} the angle in radians\n */\n angleWithSep: function(x, y) {\n return Math.atan2(\n this.x * y - this.y * x,\n this.x * x + this.y * y);\n },\n\n _matMult: function(m) {\n var x = m[0] * this.x + m[1] * this.y,\n y = m[2] * this.x + m[3] * this.y;\n this.x = x;\n this.y = y;\n return this;\n },\n\n _add: function(p) {\n this.x += p.x;\n this.y += p.y;\n return this;\n },\n\n _sub: function(p) {\n this.x -= p.x;\n this.y -= p.y;\n return this;\n },\n\n _mult: function(k) {\n this.x *= k;\n this.y *= k;\n return this;\n },\n\n _div: function(k) {\n this.x /= k;\n this.y /= k;\n return this;\n },\n\n _multByPoint: function(p) {\n this.x *= p.x;\n this.y *= p.y;\n return this;\n },\n\n _divByPoint: function(p) {\n this.x /= p.x;\n this.y /= p.y;\n return this;\n },\n\n _unit: function() {\n this._div(this.mag());\n return this;\n },\n\n _perp: function() {\n var y = this.y;\n this.y = this.x;\n this.x = -y;\n return this;\n },\n\n _rotate: function(angle) {\n var cos = Math.cos(angle),\n sin = Math.sin(angle),\n x = cos * this.x - sin * this.y,\n y = sin * this.x + cos * this.y;\n this.x = x;\n this.y = y;\n return this;\n },\n\n _rotateAround: function(angle, p) {\n var cos = Math.cos(angle),\n sin = Math.sin(angle),\n x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y),\n y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);\n this.x = x;\n this.y = y;\n return this;\n },\n\n _round: function() {\n this.x = Math.round(this.x);\n this.y = Math.round(this.y);\n return this;\n }\n};\n\n/**\n * Construct a point from an array if necessary, otherwise if the input\n * is already a Point, or an unknown type, return it unchanged\n * @param {Array|Point|*} a any kind of input value\n * @return {Point} constructed point, or passed-through value.\n * @example\n * // this\n * var point = Point.convert([0, 1]);\n * // is equivalent to\n * var point = new Point(0, 1);\n */\nPoint.convert = function (a) {\n if (a instanceof Point) {\n return a;\n }\n if (Array.isArray(a)) {\n return new Point(a[0], a[1]);\n }\n return a;\n};\n","'use strict';\n\nmodule.exports = UnitBezier;\n\nfunction UnitBezier(p1x, p1y, p2x, p2y) {\n // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).\n this.cx = 3.0 * p1x;\n this.bx = 3.0 * (p2x - p1x) - this.cx;\n this.ax = 1.0 - this.cx - this.bx;\n\n this.cy = 3.0 * p1y;\n this.by = 3.0 * (p2y - p1y) - this.cy;\n this.ay = 1.0 - this.cy - this.by;\n\n this.p1x = p1x;\n this.p1y = p1y;\n this.p2x = p2x;\n this.p2y = p2y;\n}\n\nUnitBezier.prototype = {\n sampleCurveX: function (t) {\n // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.\n return ((this.ax * t + this.bx) * t + this.cx) * t;\n },\n\n sampleCurveY: function (t) {\n return ((this.ay * t + this.by) * t + this.cy) * t;\n },\n\n sampleCurveDerivativeX: function (t) {\n return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;\n },\n\n solveCurveX: function (x, epsilon) {\n if (epsilon === undefined) epsilon = 1e-6;\n\n if (x < 0.0) return 0.0;\n if (x > 1.0) return 1.0;\n\n var t = x;\n\n // First try a few iterations of Newton's method - normally very fast.\n for (var i = 0; i < 8; i++) {\n var x2 = this.sampleCurveX(t) - x;\n if (Math.abs(x2) < epsilon) return t;\n\n var d2 = this.sampleCurveDerivativeX(t);\n if (Math.abs(d2) < 1e-6) break;\n\n t = t - x2 / d2;\n }\n\n // Fall back to the bisection method for reliability.\n var t0 = 0.0;\n var t1 = 1.0;\n t = x;\n\n for (i = 0; i < 20; i++) {\n x2 = this.sampleCurveX(t);\n if (Math.abs(x2 - x) < epsilon) break;\n\n if (x > x2) {\n t0 = t;\n } else {\n t1 = t;\n }\n\n t = (t1 - t0) * 0.5 + t0;\n }\n\n return t;\n },\n\n solve: function (x, epsilon) {\n return this.sampleCurveY(this.solveCurveX(x, epsilon));\n }\n};\n","let supportsOffscreenCanvas: boolean;\n\nexport function offscreenCanvasSupported(): boolean {\n if (supportsOffscreenCanvas == null) {\n supportsOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' &&\n new OffscreenCanvas(1, 1).getContext('2d') &&\n typeof createImageBitmap === 'function';\n }\n\n return supportsOffscreenCanvas;\n}\n","import {offscreenCanvasSupported} from './offscreen_canvas_supported';\n\nlet offscreenCanvasDistorted: boolean;\n\n/**\n * Some browsers don't return the exact pixels from a canvas to prevent user fingerprinting (see #3185).\n * This function writes pixels to an OffscreenCanvas and reads them back using getImageData, returning false\n * if they don't match.\n *\n * @returns true if the browser supports OffscreenCanvas but it distorts getImageData results, false otherwise.\n */\nexport function isOffscreenCanvasDistorted(): boolean {\n if (offscreenCanvasDistorted == null) {\n offscreenCanvasDistorted = false;\n if (offscreenCanvasSupported()) {\n const size = 5;\n const canvas = new OffscreenCanvas(size, size);\n const context = canvas.getContext('2d', {willReadFrequently: true});\n if (context) {\n // fill each pixel with an RGB value that should make the byte at index i equal to i (except alpha channel):\n // [0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 10, 255, ...]\n for (let i = 0; i < size * size; i++) {\n const base = i * 4;\n context.fillStyle = `rgb(${base},${base + 1},${base + 2})`;\n context.fillRect(i % size, Math.floor(i / size), 1, 1);\n }\n const data = context.getImageData(0, 0, size, size).data;\n for (let i = 0; i < size * size * 4; i++) {\n if (i % 4 !== 3 && data[i] !== i) {\n offscreenCanvasDistorted = true;\n break;\n }\n }\n }\n }\n }\n\n return offscreenCanvasDistorted || false;\n}\n","import Point from '@mapbox/point-geometry';\nimport UnitBezier from '@mapbox/unitbezier';\nimport {isOffscreenCanvasDistorted} from './offscreen_canvas_distorted';\nimport type {Size} from './image';\nimport type {WorkerGlobalScopeInterface} from './web_worker';\n\n/**\n * For a given collection of 2D points, returns their axis-aligned bounding box,\n * in the format [minX, minY, maxX, maxY].\n */\nexport function getAABB(points: Array): [number, number, number, number] {\n let tlX = Infinity;\n let tlY = Infinity;\n let brX = -Infinity;\n let brY = -Infinity;\n\n for (const p of points) {\n tlX = Math.min(tlX, p.x);\n tlY = Math.min(tlY, p.y);\n brX = Math.max(brX, p.x);\n brY = Math.max(brY, p.y);\n }\n\n return [tlX, tlY, brX, brY];\n}\n\n/**\n * Given a value `t` that varies between 0 and 1, return\n * an interpolation function that eases between 0 and 1 in a pleasing\n * cubic in-out fashion.\n */\nexport function easeCubicInOut(t: number): number {\n if (t <= 0) return 0;\n if (t >= 1) return 1;\n const t2 = t * t,\n t3 = t2 * t;\n return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75);\n}\n\n/**\n * Given given (x, y), (x1, y1) control points for a bezier curve,\n * return a function that interpolates along that curve.\n *\n * @param p1x - control point 1 x coordinate\n * @param p1y - control point 1 y coordinate\n * @param p2x - control point 2 x coordinate\n * @param p2y - control point 2 y coordinate\n */\nexport function bezier(p1x: number, p1y: number, p2x: number, p2y: number): (t: number) => number {\n const bezier = new UnitBezier(p1x, p1y, p2x, p2y);\n return (t: number) => {\n return bezier.solve(t);\n };\n}\n\n/**\n * A default bezier-curve powered easing function with\n * control points (0.25, 0.1) and (0.25, 1)\n */\nexport const defaultEasing = bezier(0.25, 0.1, 0.25, 1);\n\n/**\n * constrain n to the given range via min + max\n *\n * @param n - value\n * @param min - the minimum value to be returned\n * @param max - the maximum value to be returned\n * @returns the clamped value\n */\nexport function clamp(n: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, n));\n}\n\n/**\n * constrain n to the given range, excluding the minimum, via modular arithmetic\n *\n * @param n - value\n * @param min - the minimum value to be returned, exclusive\n * @param max - the maximum value to be returned, inclusive\n * @returns constrained number\n */\nexport function wrap(n: number, min: number, max: number): number {\n const d = max - min;\n const w = ((n - min) % d + d) % d + min;\n return (w === min) ? max : w;\n}\n\n/**\n * Compute the difference between the keys in one object and the keys\n * in another object.\n *\n * @returns keys difference\n */\nexport function keysDifference(\n obj: {[key: string]: S},\n other: {[key: string]: T}\n): Array {\n const difference = [];\n for (const i in obj) {\n if (!(i in other)) {\n difference.push(i);\n }\n }\n return difference;\n}\n\n/**\n * Given a destination object and optionally many source objects,\n * copy all properties from the source objects into the destination.\n * The last source object given overrides properties from previous\n * source objects.\n *\n * @param dest - destination object\n * @param sources - sources from which properties are pulled\n */\nexport function extend(dest: T, source: U): T & U;\nexport function extend(dest: T, source1: U, source2: V): T & U & V;\nexport function extend(dest: T, source1: U, source2: V, source3: W): T & U & V & W;\nexport function extend(dest: object, ...sources: Array): any;\nexport function extend(dest: object, ...sources: Array): any {\n for (const src of sources) {\n for (const k in src) {\n dest[k] = src[k];\n }\n }\n return dest;\n}\n\n// See https://stackoverflow.com/questions/49401866/all-possible-keys-of-an-union-type\ntype KeysOfUnion = T extends T ? keyof T: never;\n\n/**\n * Given an object and a number of properties as strings, return version\n * of that object with only those properties.\n *\n * @param src - the object\n * @param properties - an array of property names chosen\n * to appear on the resulting object.\n * @returns object with limited properties.\n * @example\n * ```ts\n * let foo = { name: 'Charlie', age: 10 };\n * let justName = pick(foo, ['name']); // justName = { name: 'Charlie' }\n * ```\n */\nexport function pick(src: T, properties: Array>): Partial {\n const result: Partial = {};\n for (let i = 0; i < properties.length; i++) {\n const k = properties[i];\n if (k in src) {\n result[k] = src[k];\n }\n }\n return result;\n}\n\nlet id = 1;\n\n/**\n * Return a unique numeric id, starting at 1 and incrementing with\n * each call.\n *\n * @returns unique numeric id.\n */\nexport function uniqueId(): number {\n return id++;\n}\n\n/**\n * Return whether a given value is a power of two\n */\nexport function isPowerOfTwo(value: number): boolean {\n return (Math.log(value) / Math.LN2) % 1 === 0;\n}\n\n/**\n * Return the next power of two, or the input value if already a power of two\n */\nexport function nextPowerOfTwo(value: number): number {\n if (value <= 1) return 1;\n return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));\n}\n\n/**\n * Create an object by mapping all the values of an existing object while\n * preserving their keys.\n */\nexport function mapObject(input: any, iterator: Function, context?: any): any {\n const output = {};\n for (const key in input) {\n output[key] = iterator.call(context || this, input[key], key, input);\n }\n return output;\n}\n\n/**\n * Create an object by filtering out values of an existing object.\n */\nexport function filterObject(input: any, iterator: Function, context?: any): any {\n const output = {};\n for (const key in input) {\n if (iterator.call(context || this, input[key], key, input)) {\n output[key] = input[key];\n }\n }\n return output;\n}\n\n/**\n * Deeply compares two object literals.\n * @param a - first object literal to be compared\n * @param b - second object literal to be compared\n * @returns true if the two object literals are deeply equal, false otherwise\n */\nexport function deepEqual(a?: unknown | null, b?: unknown | null): boolean {\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (typeof a === 'object' && a !== null && b !== null) {\n if (!(typeof b === 'object')) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n for (const key in a) {\n if (!deepEqual(a[key], b[key])) return false;\n }\n return true;\n }\n return a === b;\n}\n\n/**\n * Deeply clones two objects.\n */\nexport function clone(input: T): T {\n if (Array.isArray(input)) {\n return input.map(clone) as any as T;\n } else if (typeof input === 'object' && input) {\n return mapObject(input, clone) as any as T;\n } else {\n return input;\n }\n}\n\n/**\n * Check if two arrays have at least one common element.\n */\nexport function arraysIntersect(a: Array, b: Array): boolean {\n for (let l = 0; l < a.length; l++) {\n if (b.indexOf(a[l]) >= 0) return true;\n }\n return false;\n}\n\n/**\n * Print a warning message to the console and ensure duplicate warning messages\n * are not printed.\n */\nconst warnOnceHistory: {[key: string]: boolean} = {};\n\nexport function warnOnce(message: string): void {\n if (!warnOnceHistory[message]) {\n // console isn't defined in some WebWorkers, see #2558\n if (typeof console !== 'undefined') console.warn(message);\n warnOnceHistory[message] = true;\n }\n}\n\n/**\n * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order\n *\n * @returns true for a counter clockwise set of points\n */\n// https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/\nexport function isCounterClockwise(a: Point, b: Point, c: Point): boolean {\n return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);\n}\n\n/**\n * For two lines a and b in 2d space, defined by any two points along the lines,\n * find the intersection point, or return null if the lines are parallel\n *\n * @param a1 - First point on line a\n * @param a2 - Second point on line a\n * @param b1 - First point on line b\n * @param b2 - Second point on line b\n *\n * @returns the intersection point of the two lines or null if they are parallel\n */\nexport function findLineIntersection(a1: Point, a2: Point, b1: Point, b2: Point): Point | null {\n const aDeltaY = a2.y - a1.y;\n const aDeltaX = a2.x - a1.x;\n const bDeltaY = b2.y - b1.y;\n const bDeltaX = b2.x - b1.x;\n\n const denominator = (bDeltaY * aDeltaX) - (bDeltaX * aDeltaY);\n\n if (denominator === 0) {\n // Lines are parallel\n return null;\n }\n\n const originDeltaY = a1.y - b1.y;\n const originDeltaX = a1.x - b1.x;\n const aInterpolation = (bDeltaX * originDeltaY - bDeltaY * originDeltaX) / denominator;\n\n // Find intersection by projecting out from origin of first segment\n return new Point(a1.x + (aInterpolation * aDeltaX), a1.y + (aInterpolation * aDeltaY));\n}\n\n/**\n * Converts spherical coordinates to cartesian coordinates.\n *\n * @param spherical - Spherical coordinates, in [radial, azimuthal, polar]\n * @returns cartesian coordinates in [x, y, z]\n */\n\nexport function sphericalToCartesian([r, azimuthal, polar]: [number, number, number]): {\n x: number;\n y: number;\n z: number;\n} {\n // We abstract \"north\"/\"up\" (compass-wise) to be 0° when really this is 90° (π/2):\n // correct for that here\n azimuthal += 90;\n\n // Convert azimuthal and polar angles to radians\n azimuthal *= Math.PI / 180;\n polar *= Math.PI / 180;\n\n return {\n x: r * Math.cos(azimuthal) * Math.sin(polar),\n y: r * Math.sin(azimuthal) * Math.sin(polar),\n z: r * Math.cos(polar)\n };\n}\n\n/**\n * Returns true if the when run in the web-worker context.\n *\n * @returns `true` if the when run in the web-worker context.\n */\nexport function isWorker(self: any): self is WorkerGlobalScopeInterface {\n // @ts-ignore\n return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope;\n}\n\n/**\n * Parses data from 'Cache-Control' headers.\n *\n * @param cacheControl - Value of 'Cache-Control' header\n * @returns object containing parsed header info.\n */\n\nexport function parseCacheControl(cacheControl: string): any {\n // Taken from [Wreck](https://github.com/hapijs/wreck)\n const re = /(?:^|(?:\\s*\\,\\s*))([^\\x00-\\x20\\(\\)<>@\\,;\\:\\\\\"\\/\\[\\]\\?\\=\\{\\}\\x7F]+)(?:\\=(?:([^\\x00-\\x20\\(\\)<>@\\,;\\:\\\\\"\\/\\[\\]\\?\\=\\{\\}\\x7F]+)|(?:\\\"((?:[^\"\\\\]|\\\\.)*)\\\")))?/g;\n\n const header = {};\n cacheControl.replace(re, ($0, $1, $2, $3) => {\n const value = $2 || $3;\n header[$1] = value ? value.toLowerCase() : true;\n return '';\n });\n\n if (header['max-age']) {\n const maxAge = parseInt(header['max-age'], 10);\n if (isNaN(maxAge)) delete header['max-age'];\n else header['max-age'] = maxAge;\n }\n\n return header;\n}\n\nlet _isSafari = null;\n\n/**\n * Returns true when run in WebKit derived browsers.\n * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to\n * transfer data between WebWorkers and the main thread.\n * https://github.com/mapbox/mapbox-gl-js/issues/8771\n *\n * This should be removed once the underlying Safari issue is fixed.\n *\n * @param scope - Since this function is used both on the main thread and WebWorker context,\n * let the calling scope pass in the global scope object.\n * @returns `true` when run in WebKit derived browsers.\n */\nexport function isSafari(scope: any): boolean {\n if (_isSafari == null) {\n const userAgent = scope.navigator ? scope.navigator.userAgent : null;\n _isSafari = !!scope.safari ||\n !!(userAgent && (/\\b(iPad|iPhone|iPod)\\b/.test(userAgent) || (!!userAgent.match('Safari') && !userAgent.match('Chrome'))));\n }\n return _isSafari;\n}\n\nexport function storageAvailable(type: string): boolean {\n try {\n const storage = window[type];\n storage.setItem('_mapbox_test_', 1);\n storage.removeItem('_mapbox_test_');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n// The following methods are from https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem\n//Unicode compliant base64 encoder for strings\nexport function b64EncodeUnicode(str: string) {\n return btoa(\n encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n (match, p1) => {\n return String.fromCharCode(Number('0x' + p1)); //eslint-disable-line\n }\n )\n );\n}\n\n// Unicode compliant decoder for base64-encoded strings\nexport function b64DecodeUnicode(str: string) {\n return decodeURIComponent(atob(str).split('').map((c) => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); //eslint-disable-line\n }).join(''));\n}\n\nexport function isImageBitmap(image: any): image is ImageBitmap {\n return typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap;\n}\n\n/**\n * Converts an ArrayBuffer to an ImageBitmap.\n *\n * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work\n * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting\n * ArrayBuffers.\n *\n * @param data - Data to convert\n * @returns - A promise resolved when the conversion is finished\n */\nexport const arrayBufferToImageBitmap = async (data: ArrayBuffer): Promise => {\n if (data.byteLength === 0) {\n return createImageBitmap(new ImageData(1, 1));\n }\n const blob: Blob = new Blob([new Uint8Array(data)], {type: 'image/png'});\n try {\n return createImageBitmap(blob);\n } catch (e) {\n throw new Error(`Could not load image because of ${e.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`);\n }\n};\n\nconst transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=';\n\n/**\n * Converts an ArrayBuffer to an HTMLImageElement.\n *\n * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work\n * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting\n * ArrayBuffers.\n *\n * @param data - Data to convert\n * @returns - A promise resolved when the conversion is finished\n */\nexport const arrayBufferToImage = (data: ArrayBuffer): Promise => {\n return new Promise((resolve, reject) => {\n const img: HTMLImageElement = new Image();\n img.onload = () => {\n resolve(img);\n URL.revokeObjectURL(img.src);\n // prevent image dataURI memory leak in Safari;\n // but don't free the image immediately because it might be uploaded in the next frame\n // https://github.com/mapbox/mapbox-gl-js/issues/10226\n img.onload = null;\n window.requestAnimationFrame(() => { img.src = transparentPngUrl; });\n };\n img.onerror = () => reject(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.'));\n const blob: Blob = new Blob([new Uint8Array(data)], {type: 'image/png'});\n img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl;\n });\n};\n\n/**\n * Computes the webcodecs VideoFrame API options to select a rectangle out of\n * an image and write it into the destination rectangle.\n *\n * Rect (x/y/width/height) select the overlapping rectangle from the source image\n * and layout (offset/stride) write that overlapping rectangle to the correct place\n * in the destination image.\n *\n * Offset is the byte offset in the dest image that the first pixel appears at\n * and stride is the number of bytes to the start of the next row:\n * ┌───────────┐\n * │ dest │\n * │ ┌───┼───────┐\n * │offset→│▓▓▓│ source│\n * │ │▓▓▓│ │\n * │ └───┼───────┘\n * │stride ⇠╌╌╌│\n * │╌╌╌╌╌╌→ │\n * └───────────┘\n *\n * @param image - source image containing a width and height attribute\n * @param x - top-left x coordinate to read from the image\n * @param y - top-left y coordinate to read from the image\n * @param width - width of the rectangle to read from the image\n * @param height - height of the rectangle to read from the image\n * @returns the layout and rect options to pass into VideoFrame API\n */\nfunction computeVideoFrameParameters(image: Size, x: number, y: number, width: number, height: number): VideoFrameCopyToOptions {\n const destRowOffset = Math.max(-x, 0) * 4;\n const firstSourceRow = Math.max(0, y);\n const firstDestRow = firstSourceRow - y;\n const offset = firstDestRow * width * 4 + destRowOffset;\n const stride = width * 4;\n\n const sourceLeft = Math.max(0, x);\n const sourceTop = Math.max(0, y);\n const sourceRight = Math.min(image.width, x + width);\n const sourceBottom = Math.min(image.height, y + height);\n return {\n rect: {\n x: sourceLeft,\n y: sourceTop,\n width: sourceRight - sourceLeft,\n height: sourceBottom - sourceTop\n },\n layout: [{offset, stride}]\n };\n}\n\n/**\n * Reads pixels from an ImageBitmap/Image/canvas using webcodec VideoFrame API.\n *\n * @param data - image, imagebitmap, or canvas to parse\n * @param x - top-left x coordinate to read from the image\n * @param y - top-left y coordinate to read from the image\n * @param width - width of the rectangle to read from the image\n * @param height - height of the rectangle to read from the image\n * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred\n */\nexport async function readImageUsingVideoFrame(\n image: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas,\n x: number, y: number, width: number, height: number\n): Promise {\n if (typeof VideoFrame === 'undefined') {\n throw new Error('VideoFrame not supported');\n }\n const frame = new VideoFrame(image, {timestamp: 0});\n try {\n const format = frame?.format;\n if (!format || !(format.startsWith('BGR') || format.startsWith('RGB'))) {\n throw new Error(`Unrecognized format ${format}`);\n }\n const swapBR = format.startsWith('BGR');\n const result = new Uint8ClampedArray(width * height * 4);\n await frame.copyTo(result, computeVideoFrameParameters(image, x, y, width, height));\n if (swapBR) {\n for (let i = 0; i < result.length; i += 4) {\n const tmp = result[i];\n result[i] = result[i + 2];\n result[i + 2] = tmp;\n }\n }\n return result;\n } finally {\n frame.close();\n }\n}\n\nlet offscreenCanvas: OffscreenCanvas;\nlet offscreenCanvasContext: OffscreenCanvasRenderingContext2D;\n\n/**\n * Reads pixels from an ImageBitmap/Image/canvas using OffscreenCanvas\n *\n * @param data - image, imagebitmap, or canvas to parse\n * @param x - top-left x coordinate to read from the image\n * @param y - top-left y coordinate to read from the image\n * @param width - width of the rectangle to read from the image\n * @param height - height of the rectangle to read from the image\n * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred\n */\nexport function readImageDataUsingOffscreenCanvas(\n imgBitmap: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas,\n x: number, y: number, width: number, height: number\n): Uint8ClampedArray {\n const origWidth = imgBitmap.width;\n const origHeight = imgBitmap.height;\n // Lazily initialize OffscreenCanvas\n if (!offscreenCanvas || !offscreenCanvasContext) {\n // Dem tiles are typically 256x256\n offscreenCanvas = new OffscreenCanvas(origWidth, origHeight);\n offscreenCanvasContext = offscreenCanvas.getContext('2d', {willReadFrequently: true});\n }\n\n offscreenCanvas.width = origWidth;\n offscreenCanvas.height = origHeight;\n\n offscreenCanvasContext.drawImage(imgBitmap, 0, 0, origWidth, origHeight);\n const imgData = offscreenCanvasContext.getImageData(x, y, width, height);\n offscreenCanvasContext.clearRect(0, 0, origWidth, origHeight);\n return imgData.data;\n}\n\n/**\n * Reads RGBA pixels from an preferring OffscreenCanvas, but falling back to VideoFrame if supported and\n * the browser is mangling OffscreenCanvas getImageData results.\n *\n * @param data - image, imagebitmap, or canvas to parse\n * @param x - top-left x coordinate to read from the image\n * @param y - top-left y coordinate to read from the image\n * @param width - width of the rectangle to read from the image\n * @param height - height of the rectangle to read from the image\n * @returns a promise containing the parsed RGBA pixel values of the image\n */\nexport async function getImageData(\n image: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas,\n x: number, y: number, width: number, height: number\n): Promise {\n if (isOffscreenCanvasDistorted()) {\n try {\n return await readImageUsingVideoFrame(image, x, y, width, height);\n } catch (e) {\n // fall back to OffscreenCanvas\n }\n }\n return readImageDataUsingOffscreenCanvas(image, x, y, width, height);\n}\n\nexport interface Subscription {\n unsubscribe(): void;\n}\n\nexport interface Subscriber {\n addEventListener: typeof window.addEventListener;\n removeEventListener: typeof window.removeEventListener;\n}\n\n/**\n * This method is used in order to register an event listener using a lambda function.\n * The return value will allow unsubscribing from the event, without the need to store the method reference.\n * @param target - The target\n * @param message - The message\n * @param listener - The listener\n * @param options - The options\n * @returns a subscription object that can be used to unsubscribe from the event\n */\nexport function subscribe(target: Subscriber, message: keyof WindowEventMap, listener: (...args: any) => void, options: boolean | AddEventListenerOptions): Subscription {\n target.addEventListener(message, listener, options);\n return {\n unsubscribe: () => {\n target.removeEventListener(message, listener, options);\n }\n };\n}\n\n/**\n * This method converts degrees to radians.\n * The return value is the radian value.\n * @param degrees - The number of degrees\n * @returns radians\n */\nexport function degreesToRadians(degrees: number): number {\n return degrees * Math.PI / 180;\n}\n\n/**\n * Makes optional keys required and add the the undefined type.\n *\n * ```\n * interface Test {\n * foo: number;\n * bar?: number;\n * baz: number | undefined;\n * }\n *\n * Complete {\n * foo: number;\n * bar: number | undefined;\n * baz: number | undefined;\n * }\n *\n * ```\n *\n * See https://medium.com/terria/typescript-transforming-optional-properties-to-required-properties-that-may-be-undefined-7482cb4e1585\n */\n\nexport type Complete = {\n [P in keyof Required]: Pick extends Required> ? T[P] : (T[P] | undefined);\n}\n\nexport type TileJSON = {\n tilejson: '2.2.0' | '2.1.0' | '2.0.1' | '2.0.0' | '1.0.0';\n name?: string;\n description?: string;\n version?: string;\n attribution?: string;\n template?: string;\n tiles: Array;\n grids?: Array;\n data?: Array;\n minzoom?: number;\n maxzoom?: number;\n bounds?: [number, number, number, number];\n center?: [number, number, number];\n vector_layers: [{id: string}]; // this is partial but enough for what we need\n};\n\n/**\n * The maximum world tile zoom (Z).\n * In other words, the upper bound supported for tile zoom.\n */\nexport const MAX_TILE_ZOOM = 25;\n\n/**\n * The minimum world tile zoom (Z).\n * In other words, the lower bound supported for tile zoom.\n */\nexport const MIN_TILE_ZOOM = 0;\n","/**\n * An error message to use when an operation is aborted\n */\nexport const ABORT_ERROR = 'AbortError';\n\n/**\n * Check if an error is an abort error\n * @param error - An error object\n * @returns - true if the error is an abort error\n */\nexport function isAbortError(error: Error): boolean {\n return error.message === ABORT_ERROR;\n}\n\n/**\n * Use this when you need to create an abort error.\n * @returns An error object with the message \"AbortError\"\n */\nexport function createAbortError(): Error {\n return new Error(ABORT_ERROR);\n}\n","import {createAbortError} from './abort_error';\n\nconst now = typeof performance !== 'undefined' && performance && performance.now ?\n performance.now.bind(performance) :\n Date.now.bind(Date);\n\nlet linkEl;\n\nlet reducedMotionQuery: MediaQueryList;\n\n/** */\nexport const browser = {\n /**\n * Provides a function that outputs milliseconds: either performance.now()\n * or a fallback to Date.now()\n */\n now,\n\n frameAsync(abortController: AbortController): Promise {\n return new Promise((resolve, reject) => {\n const frame = requestAnimationFrame(resolve);\n abortController.signal.addEventListener('abort', () => {\n cancelAnimationFrame(frame);\n reject(createAbortError());\n });\n });\n },\n\n getImageData(img: HTMLImageElement | ImageBitmap, padding: number = 0): ImageData {\n const context = this.getImageCanvasContext(img);\n return context.getImageData(-padding, -padding, img.width as number + 2 * padding, img.height as number + 2 * padding);\n },\n\n getImageCanvasContext(img: HTMLImageElement | ImageBitmap): CanvasRenderingContext2D {\n const canvas = window.document.createElement('canvas') as HTMLCanvasElement;\n const context = canvas.getContext('2d', {willReadFrequently: true});\n if (!context) {\n throw new Error('failed to create canvas 2d context');\n }\n canvas.width = img.width as number;\n canvas.height = img.height as number;\n context.drawImage(img, 0, 0, img.width as number, img.height as number);\n return context;\n },\n\n resolveURL(path: string) {\n if (!linkEl) linkEl = document.createElement('a');\n linkEl.href = path;\n return linkEl.href;\n },\n\n hardwareConcurrency: typeof navigator !== 'undefined' && navigator.hardwareConcurrency || 4,\n\n get prefersReducedMotion(): boolean {\n // In case your test crashes when checking matchMedia, call setMatchMedia from 'src/util/test/util'\n if (!matchMedia) return false;\n //Lazily initialize media query\n if (reducedMotionQuery == null) {\n reducedMotionQuery = matchMedia('(prefers-reduced-motion: reduce)');\n }\n return reducedMotionQuery.matches;\n },\n};\n","import Point from '@mapbox/point-geometry';\n\ntype ScaleReturnValue = {\n x: number;\n y: number;\n boundingClientRect: DOMRect;\n};\n\nexport class DOM {\n private static readonly docStyle = typeof window !== 'undefined' && window.document && window.document.documentElement.style;\n\n private static userSelect: string;\n\n private static selectProp = DOM.testProp(['userSelect', 'MozUserSelect', 'WebkitUserSelect', 'msUserSelect']);\n\n private static transformProp = DOM.testProp(['transform', 'WebkitTransform']);\n\n private static testProp(props: string[]): string {\n if (!DOM.docStyle) return props[0];\n for (let i = 0; i < props.length; i++) {\n if (props[i] in DOM.docStyle) {\n return props[i];\n }\n }\n return props[0];\n }\n\n public static create(tagName: K, className?: string, container?: HTMLElement): HTMLElementTagNameMap[K] {\n const el = window.document.createElement(tagName);\n if (className !== undefined) el.className = className;\n if (container) container.appendChild(el);\n return el;\n }\n\n public static createNS(namespaceURI: string, tagName: string) {\n const el = window.document.createElementNS(namespaceURI, tagName);\n return el;\n }\n\n public static disableDrag() {\n if (DOM.docStyle && DOM.selectProp) {\n DOM.userSelect = DOM.docStyle[DOM.selectProp];\n DOM.docStyle[DOM.selectProp] = 'none';\n }\n }\n\n public static enableDrag() {\n if (DOM.docStyle && DOM.selectProp) {\n DOM.docStyle[DOM.selectProp] = DOM.userSelect;\n }\n }\n\n public static setTransform(el: HTMLElement, value: string) {\n el.style[DOM.transformProp] = value;\n }\n\n public static addEventListener(target: HTMLElement | Window | Document, type: string, callback: EventListenerOrEventListenerObject, options: {\n passive?: boolean;\n capture?: boolean;\n } = {}) {\n if ('passive' in options) {\n target.addEventListener(type, callback, options);\n } else {\n target.addEventListener(type, callback, options.capture);\n }\n }\n\n public static removeEventListener(target: HTMLElement | Window | Document, type: string, callback: EventListenerOrEventListenerObject, options: {\n passive?: boolean;\n capture?: boolean;\n } = {}) {\n if ('passive' in options) {\n target.removeEventListener(type, callback, options);\n } else {\n target.removeEventListener(type, callback, options.capture);\n }\n }\n\n // Suppress the next click, but only if it's immediate.\n private static suppressClickInternal(e) {\n e.preventDefault();\n e.stopPropagation();\n window.removeEventListener('click', DOM.suppressClickInternal, true);\n }\n\n public static suppressClick() {\n window.addEventListener('click', DOM.suppressClickInternal, true);\n window.setTimeout(() => {\n window.removeEventListener('click', DOM.suppressClickInternal, true);\n }, 0);\n }\n\n private static getScale(element: HTMLElement): ScaleReturnValue {\n const rect = element.getBoundingClientRect();\n return {\n x: (rect.width / element.offsetWidth) || 1,\n y: (rect.height / element.offsetHeight) || 1,\n boundingClientRect: rect,\n };\n }\n\n private static getPoint(el: HTMLElement, scale: ScaleReturnValue, e: MouseEvent | Touch): Point {\n const rect = scale.boundingClientRect;\n return new Point(\n // rect.left/top values are in page scale (like clientX/Y),\n // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).\n ((e.clientX - rect.left) / scale.x) - el.clientLeft,\n ((e.clientY - rect.top) / scale.y) - el.clientTop\n );\n }\n\n public static mousePos(el: HTMLElement, e: MouseEvent | Touch): Point {\n const scale = DOM.getScale(el);\n return DOM.getPoint(el, scale, e);\n }\n\n public static touchPos(el: HTMLElement, touches: TouchList) {\n const points: Point[] = [];\n const scale = DOM.getScale(el);\n for (let i = 0; i < touches.length; i++) {\n points.push(DOM.getPoint(el, scale, touches[i]));\n }\n return points;\n }\n\n public static mouseButton(e: MouseEvent) {\n return e.button;\n }\n\n public static remove(node: HTMLElement) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n}\n","import type {RequestParameters, GetResourceResponse} from './ajax';\n\n/**\n * This method type is used to register a protocol handler.\n * Use the abort controller for aborting requests.\n * Return a promise with the relevant resource response.\n */\nexport type AddProtocolAction = (requestParameters: RequestParameters, abortController: AbortController) => Promise>\n\n/**\n * This is a global config object used to store the configuration\n * It is available in the workers as well.\n * Only serializable data should be stored in it.\n */\ntype Config = {\n MAX_PARALLEL_IMAGE_REQUESTS: number;\n MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: number;\n MAX_TILE_CACHE_ZOOM_LEVELS: number;\n REGISTERED_PROTOCOLS: {[x: string]: AddProtocolAction };\n WORKER_URL: string;\n};\n\nexport const config: Config = {\n MAX_PARALLEL_IMAGE_REQUESTS: 16,\n MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: 8,\n MAX_TILE_CACHE_ZOOM_LEVELS: 5,\n REGISTERED_PROTOCOLS: {},\n WORKER_URL: ''\n};\n","import {AddProtocolAction, config} from '../util/config';\n\nexport function getProtocol(url: string) {\n return config.REGISTERED_PROTOCOLS[url.substring(0, url.indexOf('://'))];\n}\n/**\n * Adds a custom load resource function that will be called when using a URL that starts with a custom url schema.\n * This will happen in the main thread, and workers might call it if they don't know how to handle the protocol.\n * The example below will be triggered for custom:// urls defined in the sources list in the style definitions.\n * The function passed will receive the request parameters and should return with the resulting resource,\n * for example a pbf vector tile, non-compressed, represented as ArrayBuffer.\n *\n * @param customProtocol - the protocol to hook, for example 'custom'\n * @param loadFn - the function to use when trying to fetch a tile specified by the customProtocol\n * @example\n * ```ts\n * // This will fetch a file using the fetch API (this is obviously a non interesting example...)\n * addProtocol('custom', async (params, abortController) => {\n * const t = await fetch(`https://${params.url.split(\"://\")[1]}`);\n * if (t.status == 200) {\n * const buffer = await t.arrayBuffer();\n * return {data: buffer}\n * } else {\n * throw new Error(`Tile fetch error: ${t.statusText}`);\n * }\n * });\n * // the following is an example of a way to return an error when trying to load a tile\n * addProtocol('custom2', async (params, abortController) => {\n * throw new Error('someErrorMessage'));\n * });\n * ```\n */\nexport function addProtocol(customProtocol: string, loadFn: AddProtocolAction) {\n config.REGISTERED_PROTOCOLS[customProtocol] = loadFn;\n}\n\n/**\n * Removes a previously added protocol in the main thread.\n *\n * @param customProtocol - the custom protocol to remove registration for\n * @example\n * ```ts\n * removeProtocol('custom');\n * ```\n */\nexport function removeProtocol(customProtocol: string) {\n delete config.REGISTERED_PROTOCOLS[customProtocol];\n}\n","import {extend, isWorker} from './util';\nimport {createAbortError} from './abort_error';\nimport {getProtocol} from '../source/protocol_crud';\nimport {MessageType} from './actor_messages';\n\n/**\n * This is used to identify the global dispatcher id when sending a message from the worker without a target map id.\n */\nexport const GLOBAL_DISPATCHER_ID = 'global-dispatcher';\n\n/**\n * A type used to store the tile's expiration date and cache control definition\n */\nexport type ExpiryData = {cacheControl?: string | null; expires?: Date | string | null};\n\n/**\n * A `RequestParameters` object to be returned from Map.options.transformRequest callbacks.\n * @example\n * ```ts\n * // use transformRequest to modify requests that begin with `http://myHost`\n * transformRequest: function(url, resourceType) {\n * if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) {\n * return {\n * url: url.replace('http', 'https'),\n * headers: { 'my-custom-header': true },\n * credentials: 'include' // Include cookies for cross-origin requests\n * }\n * }\n * }\n * ```\n */\nexport type RequestParameters = {\n /**\n * The URL to be requested.\n */\n url: string;\n /**\n * The headers to be sent with the request.\n */\n headers?: any;\n /**\n * Request method `'GET' | 'POST' | 'PUT'`.\n */\n method?: 'GET' | 'POST' | 'PUT';\n /**\n * Request body.\n */\n body?: string;\n /**\n * Response body type to be returned.\n */\n type?: 'string' | 'json' | 'arrayBuffer' | 'image';\n /**\n * `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests.\n */\n credentials?: 'same-origin' | 'include';\n /**\n * If `true`, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events.\n */\n collectResourceTiming?: boolean;\n /**\n * Parameters supported only by browser fetch API. Property of the Request interface contains the cache mode of the request. It controls how the request will interact with the browser's HTTP cache. (https://developer.mozilla.org/en-US/docs/Web/API/Request/cache)\n */\n cache?: RequestCache;\n};\n\n/**\n * The response object returned from a successful AJAx request\n */\nexport type GetResourceResponse = ExpiryData & {\n data: T;\n}\n\n/**\n * The response callback used in various places\n */\nexport type ResponseCallback = (\n error?: Error | null,\n data?: T | null,\n cacheControl?: string | null,\n expires?: string | Date | null\n) => void;\n\n/**\n * An error thrown when a HTTP request results in an error response.\n */\nexport class AJAXError extends Error {\n /**\n * The response's HTTP status code.\n */\n status: number;\n\n /**\n * The response's HTTP status text.\n */\n statusText: string;\n\n /**\n * The request's URL.\n */\n url: string;\n\n /**\n * The response's body.\n */\n body: Blob;\n\n /**\n * @param status - The response's HTTP status code.\n * @param statusText - The response's HTTP status text.\n * @param url - The request's URL.\n * @param body - The response's body.\n */\n constructor(status: number, statusText: string, url: string, body: Blob) {\n super(`AJAXError: ${statusText} (${status}): ${url}`);\n this.status = status;\n this.statusText = statusText;\n this.url = url;\n this.body = body;\n }\n}\n\n/**\n * Ensure that we're sending the correct referrer from blob URL worker bundles.\n * For files loaded from the local file system, `location.origin` will be set\n * to the string(!) \"null\" (Firefox), or \"file://\" (Chrome, Safari, Edge),\n * and we will set an empty referrer. Otherwise, we're using the document's URL.\n */\nexport const getReferrer = () => isWorker(self) ?\n self.worker && self.worker.referrer :\n (window.location.protocol === 'blob:' ? window.parent : window).location.href;\n\n/**\n * Determines whether a URL is a file:// URL. This is obviously the case if it begins\n * with file://. Relative URLs are also file:// URLs iff the original document was loaded\n * via a file:// URL.\n * @param url - The URL to check\n * @returns `true` if the URL is a file:// URL, `false` otherwise\n */\nconst isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\\w+:/.test(url));\n\nasync function makeFetchRequest(requestParameters: RequestParameters, abortController: AbortController): Promise> {\n const request = new Request(requestParameters.url, {\n method: requestParameters.method || 'GET',\n body: requestParameters.body,\n credentials: requestParameters.credentials,\n headers: requestParameters.headers,\n cache: requestParameters.cache,\n referrer: getReferrer(),\n signal: abortController.signal\n });\n\n // If the user has already set an Accept header, do not overwrite it here\n if (requestParameters.type === 'json' && !request.headers.has('Accept')) {\n request.headers.set('Accept', 'application/json');\n }\n\n const response = await fetch(request);\n if (!response.ok) {\n const body = await response.blob();\n throw new AJAXError(response.status, response.statusText, requestParameters.url, body);\n }\n let parsePromise: Promise;\n if ((requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image')) {\n parsePromise = response.arrayBuffer();\n } else if (requestParameters.type === 'json') {\n parsePromise = response.json();\n } else {\n parsePromise = response.text();\n }\n const result = await parsePromise;\n if (abortController.signal.aborted) {\n throw createAbortError();\n }\n return {data: result, cacheControl: response.headers.get('Cache-Control'), expires: response.headers.get('Expires')};\n}\n\nfunction makeXMLHttpRequest(requestParameters: RequestParameters, abortController: AbortController): Promise> {\n return new Promise((resolve, reject) => {\n const xhr: XMLHttpRequest = new XMLHttpRequest();\n\n xhr.open(requestParameters.method || 'GET', requestParameters.url, true);\n if (requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image') {\n xhr.responseType = 'arraybuffer';\n }\n for (const k in requestParameters.headers) {\n xhr.setRequestHeader(k, requestParameters.headers[k]);\n }\n if (requestParameters.type === 'json') {\n xhr.responseType = 'text';\n // Do not overwrite the user-provided Accept header\n if (!requestParameters.headers?.Accept) {\n xhr.setRequestHeader('Accept', 'application/json');\n }\n }\n xhr.withCredentials = requestParameters.credentials === 'include';\n xhr.onerror = () => {\n reject(new Error(xhr.statusText));\n };\n xhr.onload = () => {\n if (abortController.signal.aborted) {\n return;\n }\n if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) {\n let data: unknown = xhr.response;\n if (requestParameters.type === 'json') {\n // We're manually parsing JSON here to get better error messages.\n try {\n data = JSON.parse(xhr.response);\n } catch (err) {\n reject(err);\n return;\n }\n }\n resolve({data, cacheControl: xhr.getResponseHeader('Cache-Control'), expires: xhr.getResponseHeader('Expires')});\n } else {\n const body = new Blob([xhr.response], {type: xhr.getResponseHeader('Content-Type')});\n reject(new AJAXError(xhr.status, xhr.statusText, requestParameters.url, body));\n }\n };\n abortController.signal.addEventListener('abort', () => {\n xhr.abort();\n reject(createAbortError());\n });\n xhr.send(requestParameters.body);\n });\n}\n\n/**\n * We're trying to use the Fetch API if possible. However, requests for resources with the file:// URI scheme don't work with the Fetch API.\n * In this case we unconditionally use XHR on the current thread since referrers don't matter.\n * This method can also use the registered method if `addProtocol` was called.\n * @param requestParameters - The request parameters\n * @param abortController - The abort controller allowing to cancel the request\n * @returns a promise resolving to the response, including cache control and expiry data\n */\nexport const makeRequest = function(requestParameters: RequestParameters, abortController: AbortController): Promise> {\n if (/:\\/\\//.test(requestParameters.url) && !(/^https?:|^file:/.test(requestParameters.url))) {\n const protocolLoadFn = getProtocol(requestParameters.url);\n if (protocolLoadFn) {\n return protocolLoadFn(requestParameters, abortController);\n }\n if (isWorker(self) && self.worker && self.worker.actor) {\n return self.worker.actor.sendAsync({type: MessageType.getResource, data: requestParameters, targetMapId: GLOBAL_DISPATCHER_ID}, abortController);\n }\n }\n if (!isFileURL(requestParameters.url)) {\n if (fetch && Request && AbortController && Object.prototype.hasOwnProperty.call(Request.prototype, 'signal')) {\n return makeFetchRequest(requestParameters, abortController);\n }\n if (isWorker(self) && self.worker && self.worker.actor) {\n return self.worker.actor.sendAsync({type: MessageType.getResource, data: requestParameters, mustQueue: true, targetMapId: GLOBAL_DISPATCHER_ID}, abortController);\n }\n }\n return makeXMLHttpRequest(requestParameters, abortController);\n};\n\nexport const getJSON = (requestParameters: RequestParameters, abortController: AbortController): Promise<{data: T} & ExpiryData> => {\n return makeRequest(extend(requestParameters, {type: 'json'}), abortController);\n};\n\nexport const getArrayBuffer = (requestParameters: RequestParameters, abortController: AbortController): Promise<{data: ArrayBuffer} & ExpiryData> => {\n return makeRequest(extend(requestParameters, {type: 'arrayBuffer'}), abortController);\n};\n\nexport function sameOrigin(inComingUrl: string) {\n // A relative URL \"/foo\" or \"./foo\" will throw exception in URL's ctor,\n // try-catch is expansive so just use a heuristic check to avoid it\n // also check data URL\n if (!inComingUrl ||\n inComingUrl.indexOf('://') <= 0 || // relative URL\n inComingUrl.indexOf('data:image/') === 0 || // data image URL\n inComingUrl.indexOf('blob:') === 0) { // blob\n return true;\n }\n const urlObj = new URL(inComingUrl);\n const locationObj = window.location;\n return urlObj.protocol === locationObj.protocol && urlObj.host === locationObj.host;\n}\n\nexport const getVideo = (urls: Array): Promise => {\n const video: HTMLVideoElement = window.document.createElement('video');\n video.muted = true;\n return new Promise((resolve) => {\n video.onloadstart = () => {\n resolve(video);\n };\n for (const url of urls) {\n const s: HTMLSourceElement = window.document.createElement('source');\n if (!sameOrigin(url)) {\n video.crossOrigin = 'Anonymous';\n }\n s.src = url;\n video.appendChild(s);\n }\n });\n};\n","export const webpSupported = {\n supported: false,\n testSupport\n};\n\nlet glForTesting: WebGLRenderingContext|WebGL2RenderingContext;\nlet webpCheckComplete = false;\nlet webpImgTest;\nlet webpImgTestOnloadComplete = false;\n\nif (typeof document !== 'undefined') {\n webpImgTest = document.createElement('img');\n webpImgTest.onload = () => {\n if (glForTesting) testWebpTextureUpload(glForTesting);\n glForTesting = null;\n webpImgTestOnloadComplete = true;\n };\n webpImgTest.onerror = () => {\n webpCheckComplete = true;\n glForTesting = null;\n };\n webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=';\n}\n\nfunction testSupport(gl: WebGLRenderingContext | WebGL2RenderingContext) {\n if (webpCheckComplete || !webpImgTest) return;\n\n // HTMLImageElement.complete is set when an image is done loading it's source\n // regardless of whether the load was successful or not.\n // It's possible for an error to set HTMLImageElement.complete to true which would trigger\n // testWebpTextureUpload and mistakenly set exported.supported to true in browsers which don't support webp\n // To avoid this, we set a flag in the image's onload handler and only call testWebpTextureUpload\n // after a successful image load event.\n if (webpImgTestOnloadComplete) {\n testWebpTextureUpload(gl);\n } else {\n glForTesting = gl;\n\n }\n}\n\nfunction testWebpTextureUpload(gl: WebGLRenderingContext|WebGL2RenderingContext) {\n // Edge 18 supports WebP but not uploading a WebP image to a gl texture\n // Test support for this before allowing WebP images.\n // https://github.com/mapbox/mapbox-gl-js/issues/7671\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n try {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, webpImgTest);\n\n // The error does not get triggered in Edge if the context is lost\n if (gl.isContextLost()) return;\n\n webpSupported.supported = true;\n } catch (e) {\n // Catch \"Unspecified Error.\" in Edge 18.\n }\n\n gl.deleteTexture(texture);\n\n webpCheckComplete = true;\n}\n","import {RequestParameters, makeRequest, sameOrigin, GetResourceResponse} from './ajax';\nimport {arrayBufferToImageBitmap, arrayBufferToImage, extend, isWorker, isImageBitmap} from './util';\nimport {webpSupported} from './webp_supported';\nimport {config} from './config';\nimport {createAbortError} from './abort_error';\nimport {getProtocol} from '../source/protocol_crud';\n\ntype ImageQueueThrottleControlCallback = () => boolean;\n\nexport type ImageRequestQueueItem = {\n requestParameters: RequestParameters;\n supportImageRefresh: boolean;\n state: 'queued' | 'running' | 'completed';\n abortController: AbortController;\n onError: (error: Error) => void;\n onSuccess: (response: GetResourceResponse) => void;\n}\n\ntype ImageQueueThrottleCallbackDictionary = {\n [Key: number]: ImageQueueThrottleControlCallback;\n}\n\ntype HTMLImageElementWithPriority = HTMLImageElement &\n{\n // fetchPriority is experimental property supported on Chromium browsers from Version 102\n // By default images are downloaded with priority low, whereas fetch request downloads with priority high\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/fetchPriority\n fetchPriority?: 'auto' | 'high' | 'low';\n};\n\n/**\n * By default, the image queue is self driven, meaning as soon as one requested item is processed,\n * it will move on to next one as quickly as it can while limiting\n * the number of concurrent requests to MAX_PARALLEL_IMAGE_REQUESTS. The default behavior\n * ensures that static views of the map can be rendered with minimal delay.\n *\n * However, the default behavior can prevent dynamic views of the map from rendering\n * smoothly in that many requests can finish in one render frame, putting too much pressure on GPU.\n *\n * When the view of the map is moving dynamically, smoother frame rates can be achieved\n * by throttling the number of items processed by the queue per frame. This can be\n * accomplished by using {@link addThrottleControl} to allow the caller to\n * use a lambda function to determine when the queue should be throttled (e.g. when isMoving())\n * and manually calling {@link processQueue} in the render loop.\n */\nexport namespace ImageRequest {\n let imageRequestQueue : ImageRequestQueueItem[];\n let currentParallelImageRequests:number;\n\n let throttleControlCallbackHandleCounter: number;\n let throttleControlCallbacks: ImageQueueThrottleCallbackDictionary;\n\n /**\n * Reset the image request queue, removing all pending requests.\n */\n export const resetRequestQueue = (): void => {\n imageRequestQueue = [];\n currentParallelImageRequests = 0;\n throttleControlCallbackHandleCounter = 0;\n throttleControlCallbacks = {};\n };\n\n /**\n * Install a callback to control when image queue throttling is desired.\n * (e.g. when the map view is moving)\n * @param callback - The callback function to install\n * @returns handle that identifies the installed callback.\n */\n export const addThrottleControl = (callback: ImageQueueThrottleControlCallback): number => {\n const handle = throttleControlCallbackHandleCounter++;\n throttleControlCallbacks[handle] = callback;\n return handle;\n };\n\n /**\n * Remove a previously installed callback by passing in the handle returned\n * by {@link addThrottleControl}.\n * @param callbackHandle - The handle for the callback to remove.\n */\n export const removeThrottleControl = (callbackHandle: number): void => {\n delete throttleControlCallbacks[callbackHandle];\n // Try updating the queue\n processQueue();\n };\n\n /**\n * Check to see if any of the installed callbacks are requesting the queue\n * to be throttled.\n * @returns `true` if any callback is causing the queue to be throttled.\n */\n const isThrottled = (): boolean => {\n for (const key of Object.keys(throttleControlCallbacks)) {\n if (throttleControlCallbacks[key]()) {\n return true;\n }\n }\n return false;\n };\n\n /**\n * Request to load an image.\n * @param requestParameters - Request parameters.\n * @param abortController - allows to abort the request.\n * @param supportImageRefresh - `true`, if the image request need to support refresh based on cache headers.\n * @returns - A promise resolved when the image is loaded.\n */\n export const getImage = (requestParameters: RequestParameters, abortController: AbortController, supportImageRefresh: boolean = true): Promise> => {\n return new Promise>((resolve, reject) => {\n if (webpSupported.supported) {\n if (!requestParameters.headers) {\n requestParameters.headers = {};\n }\n requestParameters.headers.accept = 'image/webp,*/*';\n }\n extend(requestParameters, {type: 'image'});\n const request: ImageRequestQueueItem = {\n abortController,\n requestParameters,\n supportImageRefresh,\n state: 'queued',\n onError: (error: Error) => {\n reject(error);\n },\n onSuccess: (response) => {\n resolve(response);\n }\n };\n\n imageRequestQueue.push(request);\n processQueue();\n });\n };\n\n const arrayBufferToCanvasImageSource = (data: ArrayBuffer): Promise => {\n const imageBitmapSupported = typeof createImageBitmap === 'function';\n if (imageBitmapSupported) {\n return arrayBufferToImageBitmap(data);\n } else {\n return arrayBufferToImage(data);\n }\n };\n\n const doImageRequest = async (itemInQueue: ImageRequestQueueItem) => {\n itemInQueue.state = 'running';\n const {requestParameters, supportImageRefresh, onError, onSuccess, abortController} = itemInQueue;\n // - If refreshExpiredTiles is false, then we can use HTMLImageElement to download raster images.\n // - Fetch/XHR (via MakeRequest API) will be used to download images for following scenarios:\n // 1. Style image sprite will had a issue with HTMLImageElement as described\n // here: https://github.com/mapbox/mapbox-gl-js/issues/1470\n // 2. If refreshExpiredTiles is true (default), then in order to read the image cache header,\n // fetch/XHR request will be required\n // - For any special case handling like use of AddProtocol, worker initiated request or additional headers\n // let makeRequest handle it.\n // - HtmlImageElement request automatically adds accept header for all the browser supported images\n const canUseHTMLImageElement = supportImageRefresh === false &&\n !isWorker(self) &&\n !getProtocol(requestParameters.url) &&\n (!requestParameters.headers ||\n Object.keys(requestParameters.headers).reduce((acc, item) => acc && item === 'accept', true));\n\n currentParallelImageRequests++;\n\n const getImagePromise = canUseHTMLImageElement ?\n getImageUsingHtmlImage(requestParameters, abortController) :\n makeRequest(requestParameters, abortController);\n\n try {\n const response = await getImagePromise;\n delete itemInQueue.abortController;\n itemInQueue.state = 'completed';\n if (response.data instanceof HTMLImageElement || isImageBitmap(response.data)) {\n // User using addProtocol can directly return HTMLImageElement/ImageBitmap type\n // If HtmlImageElement is used to get image then response type will be HTMLImageElement\n onSuccess(response as GetResourceResponse);\n } else if (response.data) {\n const img = await arrayBufferToCanvasImageSource(response.data);\n onSuccess({data: img, cacheControl: response.cacheControl, expires: response.expires});\n }\n } catch (err) {\n delete itemInQueue.abortController;\n onError(err);\n } finally {\n currentParallelImageRequests--;\n processQueue();\n }\n };\n\n /**\n * Process some number of items in the image request queue.\n */\n const processQueue = (): void => {\n\n const maxImageRequests = isThrottled() ?\n config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME :\n config.MAX_PARALLEL_IMAGE_REQUESTS;\n\n // limit concurrent image loads to help with raster sources performance on big screens\n for (let numImageRequests = currentParallelImageRequests;\n numImageRequests < maxImageRequests && imageRequestQueue.length > 0;\n numImageRequests++) {\n\n const topItemInQueue: ImageRequestQueueItem = imageRequestQueue.shift();\n if (topItemInQueue.abortController.signal.aborted) {\n numImageRequests--;\n continue;\n }\n doImageRequest(topItemInQueue);\n }\n };\n\n const getImageUsingHtmlImage = (requestParameters: RequestParameters, abortController: AbortController): Promise> => {\n return new Promise>((resolve, reject) => {\n\n const image = new Image() as HTMLImageElementWithPriority;\n const url = requestParameters.url;\n const credentials = requestParameters.credentials;\n if (credentials && credentials === 'include') {\n image.crossOrigin = 'use-credentials';\n } else if ((credentials && credentials === 'same-origin') || !sameOrigin(url)) {\n image.crossOrigin = 'anonymous';\n }\n\n abortController.signal.addEventListener('abort', () => {\n // Set src to '' to actually cancel the request\n image.src = '';\n reject(createAbortError());\n });\n\n image.fetchPriority = 'high';\n image.onload = () => {\n image.onerror = image.onload = null;\n resolve({data: image});\n };\n image.onerror = () => {\n image.onerror = image.onload = null;\n if (abortController.signal.aborted) {\n return;\n }\n reject(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.'));\n };\n image.src = url;\n });\n };\n}\n\nImageRequest.resetRequestQueue();\n","import type {RequestParameters} from './ajax';\n\n/**\n * A type of MapLibre resource.\n */\nexport const enum ResourceType {\n Glyphs = 'Glyphs',\n Image = 'Image',\n Source = 'Source',\n SpriteImage = 'SpriteImage',\n SpriteJSON = 'SpriteJSON',\n Style = 'Style',\n Tile = 'Tile',\n Unknown = 'Unknown',\n}\n\n/**\n * This function is used to tranform a request.\n * It is used just before executing the relevant request.\n */\nexport type RequestTransformFunction = (url: string, resourceType?: ResourceType) => RequestParameters | undefined;\n\nexport class RequestManager {\n _transformRequestFn: RequestTransformFunction;\n\n constructor(transformRequestFn?: RequestTransformFunction) {\n this._transformRequestFn = transformRequestFn;\n }\n\n transformRequest(url: string, type: ResourceType) {\n if (this._transformRequestFn) {\n return this._transformRequestFn(url, type) || {url};\n }\n\n return {url};\n }\n\n setTransformRequest(transformRequest: RequestTransformFunction) {\n this._transformRequestFn = transformRequest;\n }\n}\n\n","import {extend} from './util';\n\n/**\n * A listener method used as a callback to events\n */\nexport type Listener = (a: any) => any;\n\ntype Listeners = {[_: string]: Array};\n\nfunction _addEventListener(type: string, listener: Listener, listenerList: Listeners) {\n const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1;\n if (!listenerExists) {\n listenerList[type] = listenerList[type] || [];\n listenerList[type].push(listener);\n }\n}\n\nfunction _removeEventListener(type: string, listener: Listener, listenerList: Listeners) {\n if (listenerList && listenerList[type]) {\n const index = listenerList[type].indexOf(listener);\n if (index !== -1) {\n listenerList[type].splice(index, 1);\n }\n }\n}\n\n/**\n * The event class\n */\nexport class Event {\n readonly type: string;\n\n constructor(type: string, data: any = {}) {\n extend(this, data);\n this.type = type;\n }\n}\n\ninterface ErrorLike {\n message: string;\n}\n\n/**\n * An error event\n */\nexport class ErrorEvent extends Event {\n error: ErrorLike;\n\n constructor(error: ErrorLike, data: any = {}) {\n super('error', extend({error}, data));\n }\n}\n\n/**\n * Methods mixed in to other classes for event capabilities.\n *\n * @group Event Related\n */\nexport class Evented {\n _listeners: Listeners;\n _oneTimeListeners: Listeners;\n _eventedParent: Evented;\n _eventedParentData: any | (() => any);\n\n /**\n * Adds a listener to a specified event type.\n *\n * @param type - The event type to add a listen for.\n * @param listener - The function to be called when the event is fired.\n * The listener function is called with the data object passed to `fire`,\n * extended with `target` and `type` properties.\n */\n on(type: string, listener: Listener): this {\n this._listeners = this._listeners || {};\n _addEventListener(type, listener, this._listeners);\n\n return this;\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param type - The event type to remove listeners for.\n * @param listener - The listener function to remove.\n */\n off(type: string, listener: Listener) {\n _removeEventListener(type, listener, this._listeners);\n _removeEventListener(type, listener, this._oneTimeListeners);\n\n return this;\n }\n\n /**\n * Adds a listener that will be called only once to a specified event type.\n *\n * The listener will be called first time the event fires after the listener is registered.\n *\n * @param type - The event type to listen for.\n * @param listener - The function to be called when the event is fired the first time.\n * @returns `this` or a promise if a listener is not provided\n */\n once(type: string, listener?: Listener): this | Promise {\n if (!listener) {\n return new Promise((resolve) => this.once(type, resolve));\n }\n this._oneTimeListeners = this._oneTimeListeners || {};\n _addEventListener(type, listener, this._oneTimeListeners);\n\n return this;\n }\n\n fire(event: Event | string, properties?: any) {\n // Compatibility with (type: string, properties: Object) signature from previous versions.\n // See https://github.com/mapbox/mapbox-gl-js/issues/6522,\n // https://github.com/mapbox/mapbox-gl-draw/issues/766\n if (typeof event === 'string') {\n event = new Event(event, properties || {});\n }\n\n const type = event.type;\n\n if (this.listens(type)) {\n (event as any).target = this;\n\n // make sure adding or removing listeners inside other listeners won't cause an infinite loop\n const listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : [];\n for (const listener of listeners) {\n listener.call(this, event);\n }\n\n const oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : [];\n for (const listener of oneTimeListeners) {\n _removeEventListener(type, listener, this._oneTimeListeners);\n listener.call(this, event);\n }\n\n const parent = this._eventedParent;\n if (parent) {\n extend(\n event,\n typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData\n );\n parent.fire(event);\n }\n\n // To ensure that no error events are dropped, print them to the\n // console if they have no listeners.\n } else if (event instanceof ErrorEvent) {\n console.error(event.error);\n }\n\n return this;\n }\n\n /**\n * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type.\n *\n * @param type - The event type\n * @returns `true` if there is at least one registered listener for specified event type, `false` otherwise\n */\n listens(type: string): boolean {\n return (\n (this._listeners && this._listeners[type] && this._listeners[type].length > 0) ||\n (this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0) ||\n (this._eventedParent && this._eventedParent.listens(type))\n );\n }\n\n /**\n * Bubble all events fired by this instance of Evented to this parent instance of Evented.\n */\n setEventedParent(parent?: Evented | null, data?: any | (() => any)) {\n this._eventedParent = parent;\n this._eventedParentData = data;\n\n return this;\n }\n}\n","var $version = 8;\nvar $root = {\n\tversion: {\n\t\trequired: true,\n\t\ttype: \"enum\",\n\t\tvalues: [\n\t\t\t8\n\t\t]\n\t},\n\tname: {\n\t\ttype: \"string\"\n\t},\n\tmetadata: {\n\t\ttype: \"*\"\n\t},\n\tcenter: {\n\t\ttype: \"array\",\n\t\tvalue: \"number\"\n\t},\n\tzoom: {\n\t\ttype: \"number\"\n\t},\n\tbearing: {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tperiod: 360,\n\t\tunits: \"degrees\"\n\t},\n\tpitch: {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tunits: \"degrees\"\n\t},\n\tlight: {\n\t\ttype: \"light\"\n\t},\n\tsky: {\n\t\ttype: \"sky\"\n\t},\n\tprojection: {\n\t\ttype: \"projection\"\n\t},\n\tterrain: {\n\t\ttype: \"terrain\"\n\t},\n\tsources: {\n\t\trequired: true,\n\t\ttype: \"sources\"\n\t},\n\tsprite: {\n\t\ttype: \"sprite\"\n\t},\n\tglyphs: {\n\t\ttype: \"string\"\n\t},\n\ttransition: {\n\t\ttype: \"transition\"\n\t},\n\tlayers: {\n\t\trequired: true,\n\t\ttype: \"array\",\n\t\tvalue: \"layer\"\n\t}\n};\nvar sources = {\n\t\"*\": {\n\t\ttype: \"source\"\n\t}\n};\nvar source = [\n\t\"source_vector\",\n\t\"source_raster\",\n\t\"source_raster_dem\",\n\t\"source_geojson\",\n\t\"source_video\",\n\t\"source_image\"\n];\nvar source_vector = {\n\ttype: {\n\t\trequired: true,\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvector: {\n\t\t\t}\n\t\t}\n\t},\n\turl: {\n\t\ttype: \"string\"\n\t},\n\ttiles: {\n\t\ttype: \"array\",\n\t\tvalue: \"string\"\n\t},\n\tbounds: {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 4,\n\t\t\"default\": [\n\t\t\t-180,\n\t\t\t-85.051129,\n\t\t\t180,\n\t\t\t85.051129\n\t\t]\n\t},\n\tscheme: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\txyz: {\n\t\t\t},\n\t\t\ttms: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"xyz\"\n\t},\n\tminzoom: {\n\t\ttype: \"number\",\n\t\t\"default\": 0\n\t},\n\tmaxzoom: {\n\t\ttype: \"number\",\n\t\t\"default\": 22\n\t},\n\tattribution: {\n\t\ttype: \"string\"\n\t},\n\tpromoteId: {\n\t\ttype: \"promoteId\"\n\t},\n\tvolatile: {\n\t\ttype: \"boolean\",\n\t\t\"default\": false\n\t},\n\t\"*\": {\n\t\ttype: \"*\"\n\t}\n};\nvar source_raster = {\n\ttype: {\n\t\trequired: true,\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\traster: {\n\t\t\t}\n\t\t}\n\t},\n\turl: {\n\t\ttype: \"string\"\n\t},\n\ttiles: {\n\t\ttype: \"array\",\n\t\tvalue: \"string\"\n\t},\n\tbounds: {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 4,\n\t\t\"default\": [\n\t\t\t-180,\n\t\t\t-85.051129,\n\t\t\t180,\n\t\t\t85.051129\n\t\t]\n\t},\n\tminzoom: {\n\t\ttype: \"number\",\n\t\t\"default\": 0\n\t},\n\tmaxzoom: {\n\t\ttype: \"number\",\n\t\t\"default\": 22\n\t},\n\ttileSize: {\n\t\ttype: \"number\",\n\t\t\"default\": 512,\n\t\tunits: \"pixels\"\n\t},\n\tscheme: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\txyz: {\n\t\t\t},\n\t\t\ttms: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"xyz\"\n\t},\n\tattribution: {\n\t\ttype: \"string\"\n\t},\n\tvolatile: {\n\t\ttype: \"boolean\",\n\t\t\"default\": false\n\t},\n\t\"*\": {\n\t\ttype: \"*\"\n\t}\n};\nvar source_raster_dem = {\n\ttype: {\n\t\trequired: true,\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\t\"raster-dem\": {\n\t\t\t}\n\t\t}\n\t},\n\turl: {\n\t\ttype: \"string\"\n\t},\n\ttiles: {\n\t\ttype: \"array\",\n\t\tvalue: \"string\"\n\t},\n\tbounds: {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 4,\n\t\t\"default\": [\n\t\t\t-180,\n\t\t\t-85.051129,\n\t\t\t180,\n\t\t\t85.051129\n\t\t]\n\t},\n\tminzoom: {\n\t\ttype: \"number\",\n\t\t\"default\": 0\n\t},\n\tmaxzoom: {\n\t\ttype: \"number\",\n\t\t\"default\": 22\n\t},\n\ttileSize: {\n\t\ttype: \"number\",\n\t\t\"default\": 512,\n\t\tunits: \"pixels\"\n\t},\n\tattribution: {\n\t\ttype: \"string\"\n\t},\n\tencoding: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tterrarium: {\n\t\t\t},\n\t\t\tmapbox: {\n\t\t\t},\n\t\t\tcustom: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"mapbox\"\n\t},\n\tredFactor: {\n\t\ttype: \"number\",\n\t\t\"default\": 1\n\t},\n\tblueFactor: {\n\t\ttype: \"number\",\n\t\t\"default\": 1\n\t},\n\tgreenFactor: {\n\t\ttype: \"number\",\n\t\t\"default\": 1\n\t},\n\tbaseShift: {\n\t\ttype: \"number\",\n\t\t\"default\": 0\n\t},\n\tvolatile: {\n\t\ttype: \"boolean\",\n\t\t\"default\": false\n\t},\n\t\"*\": {\n\t\ttype: \"*\"\n\t}\n};\nvar source_geojson = {\n\ttype: {\n\t\trequired: true,\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tgeojson: {\n\t\t\t}\n\t\t}\n\t},\n\tdata: {\n\t\trequired: true,\n\t\ttype: \"*\"\n\t},\n\tmaxzoom: {\n\t\ttype: \"number\",\n\t\t\"default\": 18\n\t},\n\tattribution: {\n\t\ttype: \"string\"\n\t},\n\tbuffer: {\n\t\ttype: \"number\",\n\t\t\"default\": 128,\n\t\tmaximum: 512,\n\t\tminimum: 0\n\t},\n\tfilter: {\n\t\ttype: \"*\"\n\t},\n\ttolerance: {\n\t\ttype: \"number\",\n\t\t\"default\": 0.375\n\t},\n\tcluster: {\n\t\ttype: \"boolean\",\n\t\t\"default\": false\n\t},\n\tclusterRadius: {\n\t\ttype: \"number\",\n\t\t\"default\": 50,\n\t\tminimum: 0\n\t},\n\tclusterMaxZoom: {\n\t\ttype: \"number\"\n\t},\n\tclusterMinPoints: {\n\t\ttype: \"number\"\n\t},\n\tclusterProperties: {\n\t\ttype: \"*\"\n\t},\n\tlineMetrics: {\n\t\ttype: \"boolean\",\n\t\t\"default\": false\n\t},\n\tgenerateId: {\n\t\ttype: \"boolean\",\n\t\t\"default\": false\n\t},\n\tpromoteId: {\n\t\ttype: \"promoteId\"\n\t}\n};\nvar source_video = {\n\ttype: {\n\t\trequired: true,\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvideo: {\n\t\t\t}\n\t\t}\n\t},\n\turls: {\n\t\trequired: true,\n\t\ttype: \"array\",\n\t\tvalue: \"string\"\n\t},\n\tcoordinates: {\n\t\trequired: true,\n\t\ttype: \"array\",\n\t\tlength: 4,\n\t\tvalue: {\n\t\t\ttype: \"array\",\n\t\t\tlength: 2,\n\t\t\tvalue: \"number\"\n\t\t}\n\t}\n};\nvar source_image = {\n\ttype: {\n\t\trequired: true,\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\timage: {\n\t\t\t}\n\t\t}\n\t},\n\turl: {\n\t\trequired: true,\n\t\ttype: \"string\"\n\t},\n\tcoordinates: {\n\t\trequired: true,\n\t\ttype: \"array\",\n\t\tlength: 4,\n\t\tvalue: {\n\t\t\ttype: \"array\",\n\t\t\tlength: 2,\n\t\t\tvalue: \"number\"\n\t\t}\n\t}\n};\nvar layer = {\n\tid: {\n\t\ttype: \"string\",\n\t\trequired: true\n\t},\n\ttype: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tfill: {\n\t\t\t},\n\t\t\tline: {\n\t\t\t},\n\t\t\tsymbol: {\n\t\t\t},\n\t\t\tcircle: {\n\t\t\t},\n\t\t\theatmap: {\n\t\t\t},\n\t\t\t\"fill-extrusion\": {\n\t\t\t},\n\t\t\traster: {\n\t\t\t},\n\t\t\thillshade: {\n\t\t\t},\n\t\t\tbackground: {\n\t\t\t}\n\t\t},\n\t\trequired: true\n\t},\n\tmetadata: {\n\t\ttype: \"*\"\n\t},\n\tsource: {\n\t\ttype: \"string\"\n\t},\n\t\"source-layer\": {\n\t\ttype: \"string\"\n\t},\n\tminzoom: {\n\t\ttype: \"number\",\n\t\tminimum: 0,\n\t\tmaximum: 24\n\t},\n\tmaxzoom: {\n\t\ttype: \"number\",\n\t\tminimum: 0,\n\t\tmaximum: 24\n\t},\n\tfilter: {\n\t\ttype: \"filter\"\n\t},\n\tlayout: {\n\t\ttype: \"layout\"\n\t},\n\tpaint: {\n\t\ttype: \"paint\"\n\t}\n};\nvar layout = [\n\t\"layout_fill\",\n\t\"layout_line\",\n\t\"layout_circle\",\n\t\"layout_heatmap\",\n\t\"layout_fill-extrusion\",\n\t\"layout_symbol\",\n\t\"layout_raster\",\n\t\"layout_hillshade\",\n\t\"layout_background\"\n];\nvar layout_background = {\n\tvisibility: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvisible: {\n\t\t\t},\n\t\t\tnone: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"property-type\": \"constant\"\n\t}\n};\nvar layout_fill = {\n\t\"fill-sort-key\": {\n\t\ttype: \"number\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\tvisibility: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvisible: {\n\t\t\t},\n\t\t\tnone: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"property-type\": \"constant\"\n\t}\n};\nvar layout_circle = {\n\t\"circle-sort-key\": {\n\t\ttype: \"number\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\tvisibility: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvisible: {\n\t\t\t},\n\t\t\tnone: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"property-type\": \"constant\"\n\t}\n};\nvar layout_heatmap = {\n\tvisibility: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvisible: {\n\t\t\t},\n\t\t\tnone: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"property-type\": \"constant\"\n\t}\n};\nvar layout_line = {\n\t\"line-cap\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tbutt: {\n\t\t\t},\n\t\t\tround: {\n\t\t\t},\n\t\t\tsquare: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"butt\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"line-join\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tbevel: {\n\t\t\t},\n\t\t\tround: {\n\t\t\t},\n\t\t\tmiter: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"miter\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"line-miter-limit\": {\n\t\ttype: \"number\",\n\t\t\"default\": 2,\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"line-join\": \"miter\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"line-round-limit\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1.05,\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"line-join\": \"round\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"line-sort-key\": {\n\t\ttype: \"number\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\tvisibility: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvisible: {\n\t\t\t},\n\t\t\tnone: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"property-type\": \"constant\"\n\t}\n};\nvar layout_symbol = {\n\t\"symbol-placement\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tpoint: {\n\t\t\t},\n\t\t\tline: {\n\t\t\t},\n\t\t\t\"line-center\": {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"point\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"symbol-spacing\": {\n\t\ttype: \"number\",\n\t\t\"default\": 250,\n\t\tminimum: 1,\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"symbol-placement\": \"line\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"symbol-avoid-edges\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": false,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"symbol-sort-key\": {\n\t\ttype: \"number\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"symbol-z-order\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tauto: {\n\t\t\t},\n\t\t\t\"viewport-y\": {\n\t\t\t},\n\t\t\tsource: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"auto\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-allow-overlap\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": false,\n\t\trequires: [\n\t\t\t\"icon-image\",\n\t\t\t{\n\t\t\t\t\"!\": \"icon-overlap\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-overlap\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tnever: {\n\t\t\t},\n\t\t\talways: {\n\t\t\t},\n\t\t\tcooperative: {\n\t\t\t}\n\t\t},\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-ignore-placement\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": false,\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-optional\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": false,\n\t\trequires: [\n\t\t\t\"icon-image\",\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-rotation-alignment\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t},\n\t\t\tauto: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"auto\",\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-size\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tunits: \"factor of the original icon size\",\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-text-fit\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tnone: {\n\t\t\t},\n\t\t\twidth: {\n\t\t\t},\n\t\t\theight: {\n\t\t\t},\n\t\t\tboth: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"none\",\n\t\trequires: [\n\t\t\t\"icon-image\",\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-text-fit-padding\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 4,\n\t\t\"default\": [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t0\n\t\t],\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"icon-image\",\n\t\t\t\"text-field\",\n\t\t\t{\n\t\t\t\t\"icon-text-fit\": [\n\t\t\t\t\t\"both\",\n\t\t\t\t\t\"width\",\n\t\t\t\t\t\"height\"\n\t\t\t\t]\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-image\": {\n\t\ttype: \"resolvedImage\",\n\t\ttokens: true,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-rotate\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tperiod: 360,\n\t\tunits: \"degrees\",\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-padding\": {\n\t\ttype: \"padding\",\n\t\t\"default\": [\n\t\t\t2\n\t\t],\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-keep-upright\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": false,\n\t\trequires: [\n\t\t\t\"icon-image\",\n\t\t\t{\n\t\t\t\t\"icon-rotation-alignment\": \"map\"\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"symbol-placement\": [\n\t\t\t\t\t\"line\",\n\t\t\t\t\t\"line-center\"\n\t\t\t\t]\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-offset\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 2,\n\t\t\"default\": [\n\t\t\t0,\n\t\t\t0\n\t\t],\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-anchor\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tcenter: {\n\t\t\t},\n\t\t\tleft: {\n\t\t\t},\n\t\t\tright: {\n\t\t\t},\n\t\t\ttop: {\n\t\t\t},\n\t\t\tbottom: {\n\t\t\t},\n\t\t\t\"top-left\": {\n\t\t\t},\n\t\t\t\"top-right\": {\n\t\t\t},\n\t\t\t\"bottom-left\": {\n\t\t\t},\n\t\t\t\"bottom-right\": {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"center\",\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-pitch-alignment\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t},\n\t\t\tauto: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"auto\",\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-pitch-alignment\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t},\n\t\t\tauto: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"auto\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-rotation-alignment\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t},\n\t\t\t\"viewport-glyph\": {\n\t\t\t},\n\t\t\tauto: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"auto\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-field\": {\n\t\ttype: \"formatted\",\n\t\t\"default\": \"\",\n\t\ttokens: true,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-font\": {\n\t\ttype: \"array\",\n\t\tvalue: \"string\",\n\t\t\"default\": [\n\t\t\t\"Open Sans Regular\",\n\t\t\t\"Arial Unicode MS Regular\"\n\t\t],\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-size\": {\n\t\ttype: \"number\",\n\t\t\"default\": 16,\n\t\tminimum: 0,\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-max-width\": {\n\t\ttype: \"number\",\n\t\t\"default\": 10,\n\t\tminimum: 0,\n\t\tunits: \"ems\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-line-height\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1.2,\n\t\tunits: \"ems\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-letter-spacing\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tunits: \"ems\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-justify\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tauto: {\n\t\t\t},\n\t\t\tleft: {\n\t\t\t},\n\t\t\tcenter: {\n\t\t\t},\n\t\t\tright: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"center\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-radial-offset\": {\n\t\ttype: \"number\",\n\t\tunits: \"ems\",\n\t\t\"default\": 0,\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\t\"property-type\": \"data-driven\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t}\n\t},\n\t\"text-variable-anchor\": {\n\t\ttype: \"array\",\n\t\tvalue: \"enum\",\n\t\tvalues: {\n\t\t\tcenter: {\n\t\t\t},\n\t\t\tleft: {\n\t\t\t},\n\t\t\tright: {\n\t\t\t},\n\t\t\ttop: {\n\t\t\t},\n\t\t\tbottom: {\n\t\t\t},\n\t\t\t\"top-left\": {\n\t\t\t},\n\t\t\t\"top-right\": {\n\t\t\t},\n\t\t\t\"bottom-left\": {\n\t\t\t},\n\t\t\t\"bottom-right\": {\n\t\t\t}\n\t\t},\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t{\n\t\t\t\t\"symbol-placement\": [\n\t\t\t\t\t\"point\"\n\t\t\t\t]\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-variable-anchor-offset\": {\n\t\ttype: \"variableAnchorOffsetCollection\",\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t{\n\t\t\t\t\"symbol-placement\": [\n\t\t\t\t\t\"point\"\n\t\t\t\t]\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-anchor\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tcenter: {\n\t\t\t},\n\t\t\tleft: {\n\t\t\t},\n\t\t\tright: {\n\t\t\t},\n\t\t\ttop: {\n\t\t\t},\n\t\t\tbottom: {\n\t\t\t},\n\t\t\t\"top-left\": {\n\t\t\t},\n\t\t\t\"top-right\": {\n\t\t\t},\n\t\t\t\"bottom-left\": {\n\t\t\t},\n\t\t\t\"bottom-right\": {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"center\",\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t{\n\t\t\t\t\"!\": \"text-variable-anchor\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-max-angle\": {\n\t\ttype: \"number\",\n\t\t\"default\": 45,\n\t\tunits: \"degrees\",\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t{\n\t\t\t\t\"symbol-placement\": [\n\t\t\t\t\t\"line\",\n\t\t\t\t\t\"line-center\"\n\t\t\t\t]\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-writing-mode\": {\n\t\ttype: \"array\",\n\t\tvalue: \"enum\",\n\t\tvalues: {\n\t\t\thorizontal: {\n\t\t\t},\n\t\t\tvertical: {\n\t\t\t}\n\t\t},\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t{\n\t\t\t\t\"symbol-placement\": [\n\t\t\t\t\t\"point\"\n\t\t\t\t]\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-rotate\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tperiod: 360,\n\t\tunits: \"degrees\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-padding\": {\n\t\ttype: \"number\",\n\t\t\"default\": 2,\n\t\tminimum: 0,\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-keep-upright\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": true,\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t{\n\t\t\t\t\"text-rotation-alignment\": \"map\"\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"symbol-placement\": [\n\t\t\t\t\t\"line\",\n\t\t\t\t\t\"line-center\"\n\t\t\t\t]\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-transform\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tnone: {\n\t\t\t},\n\t\t\tuppercase: {\n\t\t\t},\n\t\t\tlowercase: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"none\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-offset\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tunits: \"ems\",\n\t\tlength: 2,\n\t\t\"default\": [\n\t\t\t0,\n\t\t\t0\n\t\t],\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t{\n\t\t\t\t\"!\": \"text-radial-offset\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-allow-overlap\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": false,\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t{\n\t\t\t\t\"!\": \"text-overlap\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-overlap\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tnever: {\n\t\t\t},\n\t\t\talways: {\n\t\t\t},\n\t\t\tcooperative: {\n\t\t\t}\n\t\t},\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-ignore-placement\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": false,\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-optional\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": false,\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\tvisibility: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvisible: {\n\t\t\t},\n\t\t\tnone: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"property-type\": \"constant\"\n\t}\n};\nvar layout_raster = {\n\tvisibility: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvisible: {\n\t\t\t},\n\t\t\tnone: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"property-type\": \"constant\"\n\t}\n};\nvar layout_hillshade = {\n\tvisibility: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvisible: {\n\t\t\t},\n\t\t\tnone: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"property-type\": \"constant\"\n\t}\n};\nvar filter = {\n\ttype: \"array\",\n\tvalue: \"*\"\n};\nvar filter_operator = {\n\ttype: \"enum\",\n\tvalues: {\n\t\t\"==\": {\n\t\t},\n\t\t\"!=\": {\n\t\t},\n\t\t\">\": {\n\t\t},\n\t\t\">=\": {\n\t\t},\n\t\t\"<\": {\n\t\t},\n\t\t\"<=\": {\n\t\t},\n\t\t\"in\": {\n\t\t},\n\t\t\"!in\": {\n\t\t},\n\t\tall: {\n\t\t},\n\t\tany: {\n\t\t},\n\t\tnone: {\n\t\t},\n\t\thas: {\n\t\t},\n\t\t\"!has\": {\n\t\t}\n\t}\n};\nvar geometry_type = {\n\ttype: \"enum\",\n\tvalues: {\n\t\tPoint: {\n\t\t},\n\t\tLineString: {\n\t\t},\n\t\tPolygon: {\n\t\t}\n\t}\n};\nvar function_stop = {\n\ttype: \"array\",\n\tminimum: 0,\n\tmaximum: 24,\n\tvalue: [\n\t\t\"number\",\n\t\t\"color\"\n\t],\n\tlength: 2\n};\nvar expression$1 = {\n\ttype: \"array\",\n\tvalue: \"*\",\n\tminimum: 1\n};\nvar light = {\n\tanchor: {\n\t\ttype: \"enum\",\n\t\t\"default\": \"viewport\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"property-type\": \"data-constant\",\n\t\ttransition: false,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t}\n\t},\n\tposition: {\n\t\ttype: \"array\",\n\t\t\"default\": [\n\t\t\t1.15,\n\t\t\t210,\n\t\t\t30\n\t\t],\n\t\tlength: 3,\n\t\tvalue: \"number\",\n\t\t\"property-type\": \"data-constant\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t}\n\t},\n\tcolor: {\n\t\ttype: \"color\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"default\": \"#ffffff\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\ttransition: true\n\t},\n\tintensity: {\n\t\ttype: \"number\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"default\": 0.5,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\ttransition: true\n\t}\n};\nvar sky = {\n\t\"sky-color\": {\n\t\ttype: \"color\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"default\": \"#88C6FC\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\ttransition: true\n\t},\n\t\"horizon-color\": {\n\t\ttype: \"color\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"default\": \"#ffffff\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\ttransition: true\n\t},\n\t\"fog-color\": {\n\t\ttype: \"color\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"default\": \"#ffffff\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\ttransition: true\n\t},\n\t\"fog-ground-blend\": {\n\t\ttype: \"number\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"default\": 0.5,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\ttransition: true\n\t},\n\t\"horizon-fog-blend\": {\n\t\ttype: \"number\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"default\": 0.8,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\ttransition: true\n\t},\n\t\"sky-horizon-blend\": {\n\t\ttype: \"number\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"default\": 0.8,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\ttransition: true\n\t},\n\t\"atmosphere-blend\": {\n\t\ttype: \"number\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"default\": 0.8,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\ttransition: true\n\t}\n};\nvar terrain = {\n\tsource: {\n\t\ttype: \"string\",\n\t\trequired: true\n\t},\n\texaggeration: {\n\t\ttype: \"number\",\n\t\tminimum: 0,\n\t\t\"default\": 1\n\t}\n};\nvar projection = {\n\ttype: {\n\t\ttype: \"enum\",\n\t\t\"default\": \"mercator\",\n\t\tvalues: {\n\t\t\tmercator: {\n\t\t\t},\n\t\t\tglobe: {\n\t\t\t}\n\t\t}\n\t}\n};\nvar paint = [\n\t\"paint_fill\",\n\t\"paint_line\",\n\t\"paint_circle\",\n\t\"paint_heatmap\",\n\t\"paint_fill-extrusion\",\n\t\"paint_symbol\",\n\t\"paint_raster\",\n\t\"paint_hillshade\",\n\t\"paint_background\"\n];\nvar paint_fill = {\n\t\"fill-antialias\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": true,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"fill-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"fill-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"!\": \"fill-pattern\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"fill-outline-color\": {\n\t\ttype: \"color\",\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"!\": \"fill-pattern\"\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fill-antialias\": true\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"fill-translate\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 2,\n\t\t\"default\": [\n\t\t\t0,\n\t\t\t0\n\t\t],\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"fill-translate-anchor\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"map\",\n\t\trequires: [\n\t\t\t\"fill-translate\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"fill-pattern\": {\n\t\ttype: \"resolvedImage\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"cross-faded-data-driven\"\n\t}\n};\nvar paint_line = {\n\t\"line-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"line-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"!\": \"line-pattern\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"line-translate\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 2,\n\t\t\"default\": [\n\t\t\t0,\n\t\t\t0\n\t\t],\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"line-translate-anchor\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"map\",\n\t\trequires: [\n\t\t\t\"line-translate\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"line-width\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"line-gap-width\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"line-offset\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"line-blur\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"line-dasharray\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"line widths\",\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"!\": \"line-pattern\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"cross-faded\"\n\t},\n\t\"line-pattern\": {\n\t\ttype: \"resolvedImage\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"cross-faded-data-driven\"\n\t},\n\t\"line-gradient\": {\n\t\ttype: \"color\",\n\t\ttransition: false,\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"!\": \"line-dasharray\"\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"!\": \"line-pattern\"\n\t\t\t},\n\t\t\t{\n\t\t\t\tsource: \"geojson\",\n\t\t\t\thas: {\n\t\t\t\t\tlineMetrics: true\n\t\t\t\t}\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"line-progress\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"color-ramp\"\n\t}\n};\nvar paint_circle = {\n\t\"circle-radius\": {\n\t\ttype: \"number\",\n\t\t\"default\": 5,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"circle-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"circle-blur\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"circle-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"circle-translate\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 2,\n\t\t\"default\": [\n\t\t\t0,\n\t\t\t0\n\t\t],\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"circle-translate-anchor\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"map\",\n\t\trequires: [\n\t\t\t\"circle-translate\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"circle-pitch-scale\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"map\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"circle-pitch-alignment\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"viewport\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"circle-stroke-width\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"circle-stroke-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"circle-stroke-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t}\n};\nvar paint_heatmap = {\n\t\"heatmap-radius\": {\n\t\ttype: \"number\",\n\t\t\"default\": 30,\n\t\tminimum: 1,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"heatmap-weight\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\ttransition: false,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"heatmap-intensity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"heatmap-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": [\n\t\t\t\"interpolate\",\n\t\t\t[\n\t\t\t\t\"linear\"\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"heatmap-density\"\n\t\t\t],\n\t\t\t0,\n\t\t\t\"rgba(0, 0, 255, 0)\",\n\t\t\t0.1,\n\t\t\t\"royalblue\",\n\t\t\t0.3,\n\t\t\t\"cyan\",\n\t\t\t0.5,\n\t\t\t\"lime\",\n\t\t\t0.7,\n\t\t\t\"yellow\",\n\t\t\t1,\n\t\t\t\"red\"\n\t\t],\n\t\ttransition: false,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"heatmap-density\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"color-ramp\"\n\t},\n\t\"heatmap-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t}\n};\nvar paint_symbol = {\n\t\"icon-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-halo-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"rgba(0, 0, 0, 0)\",\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-halo-width\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-halo-blur\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"icon-translate\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 2,\n\t\t\"default\": [\n\t\t\t0,\n\t\t\t0\n\t\t],\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"icon-image\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"icon-translate-anchor\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"map\",\n\t\trequires: [\n\t\t\t\"icon-image\",\n\t\t\t\"icon-translate\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\toverridable: true,\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-halo-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"rgba(0, 0, 0, 0)\",\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-halo-width\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-halo-blur\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"text-translate\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 2,\n\t\t\"default\": [\n\t\t\t0,\n\t\t\t0\n\t\t],\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\trequires: [\n\t\t\t\"text-field\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"text-translate-anchor\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"map\",\n\t\trequires: [\n\t\t\t\"text-field\",\n\t\t\t\"text-translate\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t}\n};\nvar paint_raster = {\n\t\"raster-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"raster-hue-rotate\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tperiod: 360,\n\t\ttransition: true,\n\t\tunits: \"degrees\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"raster-brightness-min\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"raster-brightness-max\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"raster-saturation\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: -1,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"raster-contrast\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: -1,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"raster-resampling\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tlinear: {\n\t\t\t},\n\t\t\tnearest: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"linear\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"raster-fade-duration\": {\n\t\ttype: \"number\",\n\t\t\"default\": 300,\n\t\tminimum: 0,\n\t\ttransition: false,\n\t\tunits: \"milliseconds\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t}\n};\nvar paint_hillshade = {\n\t\"hillshade-illumination-direction\": {\n\t\ttype: \"number\",\n\t\t\"default\": 335,\n\t\tminimum: 0,\n\t\tmaximum: 359,\n\t\ttransition: false,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"hillshade-illumination-anchor\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"viewport\",\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"hillshade-exaggeration\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0.5,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"hillshade-shadow-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"hillshade-highlight-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#FFFFFF\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"hillshade-accent-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t}\n};\nvar paint_background = {\n\t\"background-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"!\": \"background-pattern\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"background-pattern\": {\n\t\ttype: \"resolvedImage\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"cross-faded\"\n\t},\n\t\"background-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t}\n};\nvar transition = {\n\tduration: {\n\t\ttype: \"number\",\n\t\t\"default\": 300,\n\t\tminimum: 0,\n\t\tunits: \"milliseconds\"\n\t},\n\tdelay: {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\tunits: \"milliseconds\"\n\t}\n};\nvar promoteId = {\n\t\"*\": {\n\t\ttype: \"string\"\n\t}\n};\nvar v8Spec = {\n\t$version: $version,\n\t$root: $root,\n\tsources: sources,\n\tsource: source,\n\tsource_vector: source_vector,\n\tsource_raster: source_raster,\n\tsource_raster_dem: source_raster_dem,\n\tsource_geojson: source_geojson,\n\tsource_video: source_video,\n\tsource_image: source_image,\n\tlayer: layer,\n\tlayout: layout,\n\tlayout_background: layout_background,\n\tlayout_fill: layout_fill,\n\tlayout_circle: layout_circle,\n\tlayout_heatmap: layout_heatmap,\n\t\"layout_fill-extrusion\": {\n\tvisibility: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tvisible: {\n\t\t\t},\n\t\t\tnone: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"property-type\": \"constant\"\n\t}\n},\n\tlayout_line: layout_line,\n\tlayout_symbol: layout_symbol,\n\tlayout_raster: layout_raster,\n\tlayout_hillshade: layout_hillshade,\n\tfilter: filter,\n\tfilter_operator: filter_operator,\n\tgeometry_type: geometry_type,\n\t\"function\": {\n\texpression: {\n\t\ttype: \"expression\"\n\t},\n\tstops: {\n\t\ttype: \"array\",\n\t\tvalue: \"function_stop\"\n\t},\n\tbase: {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0\n\t},\n\tproperty: {\n\t\ttype: \"string\",\n\t\t\"default\": \"$zoom\"\n\t},\n\ttype: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tidentity: {\n\t\t\t},\n\t\t\texponential: {\n\t\t\t},\n\t\t\tinterval: {\n\t\t\t},\n\t\t\tcategorical: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"exponential\"\n\t},\n\tcolorSpace: {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\trgb: {\n\t\t\t},\n\t\t\tlab: {\n\t\t\t},\n\t\t\thcl: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"rgb\"\n\t},\n\t\"default\": {\n\t\ttype: \"*\",\n\t\trequired: false\n\t}\n},\n\tfunction_stop: function_stop,\n\texpression: expression$1,\n\tlight: light,\n\tsky: sky,\n\tterrain: terrain,\n\tprojection: projection,\n\tpaint: paint,\n\tpaint_fill: paint_fill,\n\t\"paint_fill-extrusion\": {\n\t\"fill-extrusion-opacity\": {\n\t\ttype: \"number\",\n\t\t\"default\": 1,\n\t\tminimum: 0,\n\t\tmaximum: 1,\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"fill-extrusion-color\": {\n\t\ttype: \"color\",\n\t\t\"default\": \"#000000\",\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t{\n\t\t\t\t\"!\": \"fill-extrusion-pattern\"\n\t\t\t}\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"fill-extrusion-translate\": {\n\t\ttype: \"array\",\n\t\tvalue: \"number\",\n\t\tlength: 2,\n\t\t\"default\": [\n\t\t\t0,\n\t\t\t0\n\t\t],\n\t\ttransition: true,\n\t\tunits: \"pixels\",\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"fill-extrusion-translate-anchor\": {\n\t\ttype: \"enum\",\n\t\tvalues: {\n\t\t\tmap: {\n\t\t\t},\n\t\t\tviewport: {\n\t\t\t}\n\t\t},\n\t\t\"default\": \"map\",\n\t\trequires: [\n\t\t\t\"fill-extrusion-translate\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t},\n\t\"fill-extrusion-pattern\": {\n\t\ttype: \"resolvedImage\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"cross-faded-data-driven\"\n\t},\n\t\"fill-extrusion-height\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\tunits: \"meters\",\n\t\ttransition: true,\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"fill-extrusion-base\": {\n\t\ttype: \"number\",\n\t\t\"default\": 0,\n\t\tminimum: 0,\n\t\tunits: \"meters\",\n\t\ttransition: true,\n\t\trequires: [\n\t\t\t\"fill-extrusion-height\"\n\t\t],\n\t\texpression: {\n\t\t\tinterpolated: true,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\",\n\t\t\t\t\"feature\",\n\t\t\t\t\"feature-state\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\t\"fill-extrusion-vertical-gradient\": {\n\t\ttype: \"boolean\",\n\t\t\"default\": true,\n\t\ttransition: false,\n\t\texpression: {\n\t\t\tinterpolated: false,\n\t\t\tparameters: [\n\t\t\t\t\"zoom\"\n\t\t\t]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t}\n},\n\tpaint_line: paint_line,\n\tpaint_circle: paint_circle,\n\tpaint_heatmap: paint_heatmap,\n\tpaint_symbol: paint_symbol,\n\tpaint_raster: paint_raster,\n\tpaint_hillshade: paint_hillshade,\n\tpaint_background: paint_background,\n\ttransition: transition,\n\t\"property-type\": {\n\t\"data-driven\": {\n\t\ttype: \"property-type\"\n\t},\n\t\"cross-faded\": {\n\t\ttype: \"property-type\"\n\t},\n\t\"cross-faded-data-driven\": {\n\t\ttype: \"property-type\"\n\t},\n\t\"color-ramp\": {\n\t\ttype: \"property-type\"\n\t},\n\t\"data-constant\": {\n\t\ttype: \"property-type\"\n\t},\n\tconstant: {\n\t\ttype: \"property-type\"\n\t}\n},\n\tpromoteId: promoteId\n};\n\nconst refProperties = ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout'];\n\nfunction deref(layer, parent) {\n const result = {};\n for (const k in layer) {\n if (k !== 'ref') {\n result[k] = layer[k];\n }\n }\n refProperties.forEach((k) => {\n if (k in parent) {\n result[k] = parent[k];\n }\n });\n return result;\n}\n/**\n * Given an array of layers, some of which may contain `ref` properties\n * whose value is the `id` of another property, return a new array where\n * such layers have been augmented with the 'type', 'source', etc. properties\n * from the parent layer, and the `ref` property has been removed.\n *\n * The input is not modified. The output may contain references to portions\n * of the input.\n *\n * @private\n * @param {Array} layers\n * @returns {Array}\n */\nfunction derefLayers(layers) {\n layers = layers.slice();\n const map = Object.create(null);\n for (let i = 0; i < layers.length; i++) {\n map[layers[i].id] = layers[i];\n }\n for (let i = 0; i < layers.length; i++) {\n if ('ref' in layers[i]) {\n layers[i] = deref(layers[i], map[layers[i].ref]);\n }\n }\n return layers;\n}\n\n/**\n * Deeply compares two object literals.\n *\n * @private\n */\nfunction deepEqual(a, b) {\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length)\n return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i]))\n return false;\n }\n return true;\n }\n if (typeof a === 'object' && a !== null && b !== null) {\n if (!(typeof b === 'object'))\n return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length)\n return false;\n for (const key in a) {\n if (!deepEqual(a[key], b[key]))\n return false;\n }\n return true;\n }\n return a === b;\n}\n\n/**\n * The main reason for this method is to allow type check when adding a command to the array.\n * @param commands - The commands array to add to\n * @param command - The command to add\n */\nfunction addCommand(commands, command) {\n commands.push(command);\n}\nfunction addSource(sourceId, after, commands) {\n addCommand(commands, { command: 'addSource', args: [sourceId, after[sourceId]] });\n}\nfunction removeSource(sourceId, commands, sourcesRemoved) {\n addCommand(commands, { command: 'removeSource', args: [sourceId] });\n sourcesRemoved[sourceId] = true;\n}\nfunction updateSource(sourceId, after, commands, sourcesRemoved) {\n removeSource(sourceId, commands, sourcesRemoved);\n addSource(sourceId, after, commands);\n}\nfunction canUpdateGeoJSON(before, after, sourceId) {\n let prop;\n for (prop in before[sourceId]) {\n if (!Object.prototype.hasOwnProperty.call(before[sourceId], prop))\n continue;\n if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n for (prop in after[sourceId]) {\n if (!Object.prototype.hasOwnProperty.call(after[sourceId], prop))\n continue;\n if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n return true;\n}\nfunction diffSources(before, after, commands, sourcesRemoved) {\n before = before || {};\n after = after || {};\n let sourceId;\n // look for sources to remove\n for (sourceId in before) {\n if (!Object.prototype.hasOwnProperty.call(before, sourceId))\n continue;\n if (!Object.prototype.hasOwnProperty.call(after, sourceId)) {\n removeSource(sourceId, commands, sourcesRemoved);\n }\n }\n // look for sources to add/update\n for (sourceId in after) {\n if (!Object.prototype.hasOwnProperty.call(after, sourceId))\n continue;\n if (!Object.prototype.hasOwnProperty.call(before, sourceId)) {\n addSource(sourceId, after, commands);\n }\n else if (!deepEqual(before[sourceId], after[sourceId])) {\n if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) {\n addCommand(commands, { command: 'setGeoJSONSourceData', args: [sourceId, after[sourceId].data] });\n }\n else {\n // no update command, must remove then add\n updateSource(sourceId, after, commands, sourcesRemoved);\n }\n }\n }\n}\nfunction diffLayerPropertyChanges(before, after, commands, layerId, klass, command) {\n before = before || {};\n after = after || {};\n for (const prop in before) {\n if (!Object.prototype.hasOwnProperty.call(before, prop))\n continue;\n if (!deepEqual(before[prop], after[prop])) {\n commands.push({ command, args: [layerId, prop, after[prop], klass] });\n }\n }\n for (const prop in after) {\n if (!Object.prototype.hasOwnProperty.call(after, prop) || Object.prototype.hasOwnProperty.call(before, prop))\n continue;\n if (!deepEqual(before[prop], after[prop])) {\n commands.push({ command, args: [layerId, prop, after[prop], klass] });\n }\n }\n}\nfunction pluckId(layer) {\n return layer.id;\n}\nfunction indexById(group, layer) {\n group[layer.id] = layer;\n return group;\n}\nfunction diffLayers(before, after, commands) {\n before = before || [];\n after = after || [];\n // order of layers by id\n const beforeOrder = before.map(pluckId);\n const afterOrder = after.map(pluckId);\n // index of layer by id\n const beforeIndex = before.reduce(indexById, {});\n const afterIndex = after.reduce(indexById, {});\n // track order of layers as if they have been mutated\n const tracker = beforeOrder.slice();\n // layers that have been added do not need to be diffed\n const clean = Object.create(null);\n let layerId;\n let beforeLayer;\n let afterLayer;\n let insertBeforeLayerId;\n let prop;\n // remove layers\n for (let i = 0, d = 0; i < beforeOrder.length; i++) {\n layerId = beforeOrder[i];\n if (!Object.prototype.hasOwnProperty.call(afterIndex, layerId)) {\n addCommand(commands, { command: 'removeLayer', args: [layerId] });\n tracker.splice(tracker.indexOf(layerId, d), 1);\n }\n else {\n // limit where in tracker we need to look for a match\n d++;\n }\n }\n // add/reorder layers\n for (let i = 0, d = 0; i < afterOrder.length; i++) {\n // work backwards as insert is before an existing layer\n layerId = afterOrder[afterOrder.length - 1 - i];\n if (tracker[tracker.length - 1 - i] === layerId)\n continue;\n if (Object.prototype.hasOwnProperty.call(beforeIndex, layerId)) {\n // remove the layer before we insert at the correct position\n addCommand(commands, { command: 'removeLayer', args: [layerId] });\n tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);\n }\n else {\n // limit where in tracker we need to look for a match\n d++;\n }\n // add layer at correct position\n insertBeforeLayerId = tracker[tracker.length - i];\n addCommand(commands, { command: 'addLayer', args: [afterIndex[layerId], insertBeforeLayerId] });\n tracker.splice(tracker.length - i, 0, layerId);\n clean[layerId] = true;\n }\n // update layers\n for (let i = 0; i < afterOrder.length; i++) {\n layerId = afterOrder[i];\n beforeLayer = beforeIndex[layerId];\n afterLayer = afterIndex[layerId];\n // no need to update if previously added (new or moved)\n if (clean[layerId] || deepEqual(beforeLayer, afterLayer))\n continue;\n // If source, source-layer, or type have changes, then remove the layer\n // and add it back 'from scratch'.\n if (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !deepEqual(beforeLayer.type, afterLayer.type)) {\n addCommand(commands, { command: 'removeLayer', args: [layerId] });\n // we add the layer back at the same position it was already in, so\n // there's no need to update the `tracker`\n insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];\n addCommand(commands, { command: 'addLayer', args: [afterLayer, insertBeforeLayerId] });\n continue;\n }\n // layout, paint, filter, minzoom, maxzoom\n diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, 'setLayoutProperty');\n diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, 'setPaintProperty');\n if (!deepEqual(beforeLayer.filter, afterLayer.filter)) {\n addCommand(commands, { command: 'setFilter', args: [layerId, afterLayer.filter] });\n }\n if (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) {\n addCommand(commands, { command: 'setLayerZoomRange', args: [layerId, afterLayer.minzoom, afterLayer.maxzoom] });\n }\n // handle all other layer props, including paint.*\n for (prop in beforeLayer) {\n if (!Object.prototype.hasOwnProperty.call(beforeLayer, prop))\n continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom')\n continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty');\n }\n else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) {\n addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] });\n }\n }\n for (prop in afterLayer) {\n if (!Object.prototype.hasOwnProperty.call(afterLayer, prop) || Object.prototype.hasOwnProperty.call(beforeLayer, prop))\n continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom')\n continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty');\n }\n else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) {\n addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] });\n }\n }\n }\n}\n/**\n * Diff two stylesheet\n *\n * Creates semanticly aware diffs that can easily be applied at runtime.\n * Operations produced by the diff closely resemble the maplibre-gl-js API. Any\n * error creating the diff will fall back to the 'setStyle' operation.\n *\n * Example diff:\n * [\n * { command: 'setConstant', args: ['@water', '#0000FF'] },\n * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] }\n * ]\n *\n * @private\n * @param {*} [before] stylesheet to compare from\n * @param {*} after stylesheet to compare to\n * @returns Array list of changes\n */\nfunction diffStyles(before, after) {\n if (!before)\n return [{ command: 'setStyle', args: [after] }];\n let commands = [];\n try {\n // Handle changes to top-level properties\n if (!deepEqual(before.version, after.version)) {\n return [{ command: 'setStyle', args: [after] }];\n }\n if (!deepEqual(before.center, after.center)) {\n commands.push({ command: 'setCenter', args: [after.center] });\n }\n if (!deepEqual(before.zoom, after.zoom)) {\n commands.push({ command: 'setZoom', args: [after.zoom] });\n }\n if (!deepEqual(before.bearing, after.bearing)) {\n commands.push({ command: 'setBearing', args: [after.bearing] });\n }\n if (!deepEqual(before.pitch, after.pitch)) {\n commands.push({ command: 'setPitch', args: [after.pitch] });\n }\n if (!deepEqual(before.sprite, after.sprite)) {\n commands.push({ command: 'setSprite', args: [after.sprite] });\n }\n if (!deepEqual(before.glyphs, after.glyphs)) {\n commands.push({ command: 'setGlyphs', args: [after.glyphs] });\n }\n if (!deepEqual(before.transition, after.transition)) {\n commands.push({ command: 'setTransition', args: [after.transition] });\n }\n if (!deepEqual(before.light, after.light)) {\n commands.push({ command: 'setLight', args: [after.light] });\n }\n if (!deepEqual(before.terrain, after.terrain)) {\n commands.push({ command: 'setTerrain', args: [after.terrain] });\n }\n if (!deepEqual(before.sky, after.sky)) {\n commands.push({ command: 'setSky', args: [after.sky] });\n }\n if (!deepEqual(before.projection, after.projection)) {\n commands.push({ command: 'setProjection', args: [after.projection] });\n }\n // Handle changes to `sources`\n // If a source is to be removed, we also--before the removeSource\n // command--need to remove all the style layers that depend on it.\n const sourcesRemoved = {};\n // First collect the {add,remove}Source commands\n const removeOrAddSourceCommands = [];\n diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);\n // Push a removeLayer command for each style layer that depends on a\n // source that's being removed.\n // Also, exclude any such layers them from the input to `diffLayers`\n // below, so that diffLayers produces the appropriate `addLayers`\n // command\n const beforeLayers = [];\n if (before.layers) {\n before.layers.forEach((layer) => {\n if ('source' in layer && sourcesRemoved[layer.source]) {\n commands.push({ command: 'removeLayer', args: [layer.id] });\n }\n else {\n beforeLayers.push(layer);\n }\n });\n }\n commands = commands.concat(removeOrAddSourceCommands);\n // Handle changes to `layers`\n diffLayers(beforeLayers, after.layers, commands);\n }\n catch (e) {\n // fall back to setStyle\n console.warn('Unable to compute style diff:', e);\n commands = [{ command: 'setStyle', args: [after] }];\n }\n return commands;\n}\n\n// Note: Do not inherit from Error. It breaks when transpiling to ES5.\nclass ValidationError {\n constructor(key, value, message, identifier) {\n this.message = (key ? `${key}: ` : '') + message;\n if (identifier)\n this.identifier = identifier;\n if (value !== null && value !== undefined && value.__line__) {\n this.line = value.__line__;\n }\n }\n}\n\n// Note: Do not inherit from Error. It breaks when transpiling to ES5.\nclass ParsingError {\n constructor(error) {\n this.error = error;\n this.message = error.message;\n const match = error.message.match(/line (\\d+)/);\n this.line = match ? parseInt(match[1], 10) : 0;\n }\n}\n\nfunction extendBy(output, ...inputs) {\n for (const input of inputs) {\n for (const k in input) {\n output[k] = input[k];\n }\n }\n return output;\n}\n\nclass ExpressionParsingError extends Error {\n constructor(key, message) {\n super(message);\n this.message = message;\n this.key = key;\n }\n}\n\n/**\n * Tracks `let` bindings during expression parsing.\n * @private\n */\nclass Scope {\n constructor(parent, bindings = []) {\n this.parent = parent;\n this.bindings = {};\n for (const [name, expression] of bindings) {\n this.bindings[name] = expression;\n }\n }\n concat(bindings) {\n return new Scope(this, bindings);\n }\n get(name) {\n if (this.bindings[name]) {\n return this.bindings[name];\n }\n if (this.parent) {\n return this.parent.get(name);\n }\n throw new Error(`${name} not found in scope.`);\n }\n has(name) {\n if (this.bindings[name])\n return true;\n return this.parent ? this.parent.has(name) : false;\n }\n}\n\nconst NullType = { kind: 'null' };\nconst NumberType = { kind: 'number' };\nconst StringType = { kind: 'string' };\nconst BooleanType = { kind: 'boolean' };\nconst ColorType = { kind: 'color' };\nconst ObjectType = { kind: 'object' };\nconst ValueType = { kind: 'value' };\nconst ErrorType = { kind: 'error' };\nconst CollatorType = { kind: 'collator' };\nconst FormattedType = { kind: 'formatted' };\nconst PaddingType = { kind: 'padding' };\nconst ResolvedImageType = { kind: 'resolvedImage' };\nconst VariableAnchorOffsetCollectionType = { kind: 'variableAnchorOffsetCollection' };\nfunction array$1(itemType, N) {\n return {\n kind: 'array',\n itemType,\n N\n };\n}\nfunction toString$1(type) {\n if (type.kind === 'array') {\n const itemType = toString$1(type.itemType);\n return typeof type.N === 'number' ?\n `array<${itemType}, ${type.N}>` :\n type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`;\n }\n else {\n return type.kind;\n }\n}\nconst valueMemberTypes = [\n NullType,\n NumberType,\n StringType,\n BooleanType,\n ColorType,\n FormattedType,\n ObjectType,\n array$1(ValueType),\n PaddingType,\n ResolvedImageType,\n VariableAnchorOffsetCollectionType\n];\n/**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message.\n * @private\n */\nfunction checkSubtype(expected, t) {\n if (t.kind === 'error') {\n // Error is a subtype of every type\n return null;\n }\n else if (expected.kind === 'array') {\n if (t.kind === 'array' &&\n ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) &&\n (typeof expected.N !== 'number' || expected.N === t.N)) {\n return null;\n }\n }\n else if (expected.kind === t.kind) {\n return null;\n }\n else if (expected.kind === 'value') {\n for (const memberType of valueMemberTypes) {\n if (!checkSubtype(memberType, t)) {\n return null;\n }\n }\n }\n return `Expected ${toString$1(expected)} but found ${toString$1(t)} instead.`;\n}\nfunction isValidType(provided, allowedTypes) {\n return allowedTypes.some(t => t.kind === provided.kind);\n}\nfunction isValidNativeType(provided, allowedTypes) {\n return allowedTypes.some(t => {\n if (t === 'null') {\n return provided === null;\n }\n else if (t === 'array') {\n return Array.isArray(provided);\n }\n else if (t === 'object') {\n return provided && !Array.isArray(provided) && typeof provided === 'object';\n }\n else {\n return t === typeof provided;\n }\n });\n}\n/**\n * Verify whether the specified type is of the same type as the specified sample.\n *\n * @param provided Type to verify\n * @param sample Sample type to reference\n * @returns `true` if both objects are of the same type, `false` otherwise\n * @example basic types\n * if (verifyType(outputType, ValueType)) {\n * // type narrowed to:\n * outputType.kind; // 'value'\n * }\n * @example array types\n * if (verifyType(outputType, array(NumberType))) {\n * // type narrowed to:\n * outputType.kind; // 'array'\n * outputType.itemType; // NumberTypeT\n * outputType.itemType.kind; // 'number'\n * }\n */\nfunction verifyType(provided, sample) {\n if (provided.kind === 'array' && sample.kind === 'array') {\n return provided.itemType.kind === sample.itemType.kind && typeof provided.N === 'number';\n }\n return provided.kind === sample.kind;\n}\n\n// See https://observablehq.com/@mbostock/lab-and-rgb\nconst Xn = 0.96422, Yn = 1, Zn = 0.82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI;\nfunction constrainAngle(angle) {\n angle = angle % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\nfunction rgbToLab([r, g, b, alpha]) {\n r = rgb2xyz(r);\n g = rgb2xyz(g);\n b = rgb2xyz(b);\n let x, z;\n const y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn);\n if (r === g && g === b) {\n x = z = y;\n }\n else {\n x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);\n z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);\n }\n const l = 116 * y - 16;\n return [(l < 0) ? 0 : l, 500 * (x - y), 200 * (y - z), alpha];\n}\nfunction rgb2xyz(x) {\n return (x <= 0.04045) ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\nfunction xyz2lab(t) {\n return (t > t3) ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\nfunction labToRgb([l, a, b, alpha]) {\n let y = (l + 16) / 116, x = isNaN(a) ? y : y + a / 500, z = isNaN(b) ? y : y - b / 200;\n y = Yn * lab2xyz(y);\n x = Xn * lab2xyz(x);\n z = Zn * lab2xyz(z);\n return [\n xyz2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), // D50 -> sRGB\n xyz2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),\n xyz2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z),\n alpha,\n ];\n}\nfunction xyz2rgb(x) {\n x = (x <= 0.00304) ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055;\n return (x < 0) ? 0 : (x > 1) ? 1 : x; // clip to 0..1 range\n}\nfunction lab2xyz(t) {\n return (t > t1) ? t * t * t : t2 * (t - t0);\n}\nfunction rgbToHcl(rgbColor) {\n const [l, a, b, alpha] = rgbToLab(rgbColor);\n const c = Math.sqrt(a * a + b * b);\n const h = Math.round(c * 10000) ? constrainAngle(Math.atan2(b, a) * rad2deg) : NaN;\n return [h, c, l, alpha];\n}\nfunction hclToRgb([h, c, l, alpha]) {\n h = isNaN(h) ? 0 : h * deg2rad;\n return labToRgb([l, Math.cos(h) * c, Math.sin(h) * c, alpha]);\n}\n// https://drafts.csswg.org/css-color-4/#hsl-to-rgb\nfunction hslToRgb([h, s, l, alpha]) {\n h = constrainAngle(h);\n s /= 100;\n l /= 100;\n function f(n) {\n const k = (n + h / 30) % 12;\n const a = s * Math.min(l, 1 - l);\n return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));\n }\n return [f(0), f(8), f(4), alpha];\n}\n\n/**\n * CSS color parser compliant with CSS Color 4 Specification.\n * Supports: named colors, `transparent` keyword, all rgb hex notations,\n * rgb(), rgba(), hsl() and hsla() functions.\n * Does not round the parsed values to integers from the range 0..255.\n *\n * Syntax:\n *\n * = | \n * = | \n *\n * rgb() = rgb( {3} [ / ]? ) | rgb( {3} [ / ]? )\n * rgb() = rgb( #{3} , ? ) | rgb( #{3} , ? )\n *\n * hsl() = hsl( [ / ]? )\n * hsl() = hsl( , , , ? )\n *\n * Caveats:\n * - - with optional `deg` suffix; `grad`, `rad`, `turn` are not supported\n * - `none` keyword is not supported\n * - comments inside rgb()/hsl() are not supported\n * - legacy color syntax rgba() is supported with an identical grammar and behavior to rgb()\n * - legacy color syntax hsla() is supported with an identical grammar and behavior to hsl()\n *\n * @param input CSS color string to parse.\n * @returns Color in sRGB color space, with `red`, `green`, `blue`\n * and `alpha` channels normalized to the range 0..1,\n * or `undefined` if the input is not a valid color string.\n */\nfunction parseCssColor(input) {\n input = input.toLowerCase().trim();\n if (input === 'transparent') {\n return [0, 0, 0, 0];\n }\n // 'white', 'black', 'blue'\n const namedColorsMatch = namedColors[input];\n if (namedColorsMatch) {\n const [r, g, b] = namedColorsMatch;\n return [r / 255, g / 255, b / 255, 1];\n }\n // #f0c, #f0cf, #ff00cc, #ff00ccff\n if (input.startsWith('#')) {\n const hexRegexp = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/;\n if (hexRegexp.test(input)) {\n const step = input.length < 6 ? 1 : 2;\n let i = 1;\n return [\n parseHex(input.slice(i, i += step)),\n parseHex(input.slice(i, i += step)),\n parseHex(input.slice(i, i += step)),\n parseHex(input.slice(i, i + step) || 'ff'),\n ];\n }\n }\n // rgb(128 0 0), rgb(50% 0% 0%), rgba(255,0,255,0.6), rgb(255 0 255 / 60%), rgb(100% 0% 100% /.6)\n if (input.startsWith('rgb')) {\n const rgbRegExp = /^rgba?\\(\\s*([\\de.+-]+)(%)?(?:\\s+|\\s*(,)\\s*)([\\de.+-]+)(%)?(?:\\s+|\\s*(,)\\s*)([\\de.+-]+)(%)?(?:\\s*([,\\/])\\s*([\\de.+-]+)(%)?)?\\s*\\)$/;\n const rgbMatch = input.match(rgbRegExp);\n if (rgbMatch) {\n const [_, // eslint-disable-line @typescript-eslint/no-unused-vars\n r, // \n rp, // % (optional)\n f1, // , (optional)\n g, // \n gp, // % (optional)\n f2, // , (optional)\n b, // \n bp, // % (optional)\n f3, // ,|/ (optional)\n a, // (optional)\n ap, // % (optional)\n ] = rgbMatch;\n const argFormat = [f1 || ' ', f2 || ' ', f3].join('');\n if (argFormat === ' ' ||\n argFormat === ' /' ||\n argFormat === ',,' ||\n argFormat === ',,,') {\n const valFormat = [rp, gp, bp].join('');\n const maxValue = (valFormat === '%%%') ? 100 :\n (valFormat === '') ? 255 : 0;\n if (maxValue) {\n const rgba = [\n clamp(+r / maxValue, 0, 1),\n clamp(+g / maxValue, 0, 1),\n clamp(+b / maxValue, 0, 1),\n a ? parseAlpha(+a, ap) : 1,\n ];\n if (validateNumbers(rgba)) {\n return rgba;\n }\n // invalid numbers\n }\n // values must be all numbers or all percentages\n }\n return; // comma optional syntax requires no commas at all\n }\n }\n // hsl(120 50% 80%), hsla(120deg,50%,80%,.9), hsl(12e1 50% 80% / 90%)\n const hslRegExp = /^hsla?\\(\\s*([\\de.+-]+)(?:deg)?(?:\\s+|\\s*(,)\\s*)([\\de.+-]+)%(?:\\s+|\\s*(,)\\s*)([\\de.+-]+)%(?:\\s*([,\\/])\\s*([\\de.+-]+)(%)?)?\\s*\\)$/;\n const hslMatch = input.match(hslRegExp);\n if (hslMatch) {\n const [_, // eslint-disable-line @typescript-eslint/no-unused-vars\n h, // \n f1, // , (optional)\n s, // \n f2, // , (optional)\n l, // \n f3, // ,|/ (optional)\n a, // (optional)\n ap, // % (optional)\n ] = hslMatch;\n const argFormat = [f1 || ' ', f2 || ' ', f3].join('');\n if (argFormat === ' ' ||\n argFormat === ' /' ||\n argFormat === ',,' ||\n argFormat === ',,,') {\n const hsla = [\n +h,\n clamp(+s, 0, 100),\n clamp(+l, 0, 100),\n a ? parseAlpha(+a, ap) : 1,\n ];\n if (validateNumbers(hsla)) {\n return hslToRgb(hsla);\n }\n // invalid numbers\n }\n // comma optional syntax requires no commas at all\n }\n}\nfunction parseHex(hex) {\n return parseInt(hex.padEnd(2, hex), 16) / 255;\n}\nfunction parseAlpha(a, asPercentage) {\n return clamp(asPercentage ? (a / 100) : a, 0, 1);\n}\nfunction clamp(n, min, max) {\n return Math.min(Math.max(min, n), max);\n}\n/**\n * The regular expression for numeric values is not super specific, and it may\n * happen that it will accept a value that is not a valid number. In order to\n * detect and eliminate such values this function exists.\n *\n * @param array Array of uncertain numbers.\n * @returns `true` if the specified array contains only valid numbers, `false` otherwise.\n */\nfunction validateNumbers(array) {\n return !array.some(Number.isNaN);\n}\n/**\n * To generate:\n * - visit {@link https://www.w3.org/TR/css-color-4/#named-colors}\n * - run in the console:\n * @example\n * copy(`{\\n${[...document.querySelector('.named-color-table tbody').children].map((tr) => `${tr.cells[2].textContent.trim()}: [${tr.cells[4].textContent.trim().split(/\\s+/).join(', ')}],`).join('\\n')}\\n}`);\n */\nconst namedColors = {\n aliceblue: [240, 248, 255],\n antiquewhite: [250, 235, 215],\n aqua: [0, 255, 255],\n aquamarine: [127, 255, 212],\n azure: [240, 255, 255],\n beige: [245, 245, 220],\n bisque: [255, 228, 196],\n black: [0, 0, 0],\n blanchedalmond: [255, 235, 205],\n blue: [0, 0, 255],\n blueviolet: [138, 43, 226],\n brown: [165, 42, 42],\n burlywood: [222, 184, 135],\n cadetblue: [95, 158, 160],\n chartreuse: [127, 255, 0],\n chocolate: [210, 105, 30],\n coral: [255, 127, 80],\n cornflowerblue: [100, 149, 237],\n cornsilk: [255, 248, 220],\n crimson: [220, 20, 60],\n cyan: [0, 255, 255],\n darkblue: [0, 0, 139],\n darkcyan: [0, 139, 139],\n darkgoldenrod: [184, 134, 11],\n darkgray: [169, 169, 169],\n darkgreen: [0, 100, 0],\n darkgrey: [169, 169, 169],\n darkkhaki: [189, 183, 107],\n darkmagenta: [139, 0, 139],\n darkolivegreen: [85, 107, 47],\n darkorange: [255, 140, 0],\n darkorchid: [153, 50, 204],\n darkred: [139, 0, 0],\n darksalmon: [233, 150, 122],\n darkseagreen: [143, 188, 143],\n darkslateblue: [72, 61, 139],\n darkslategray: [47, 79, 79],\n darkslategrey: [47, 79, 79],\n darkturquoise: [0, 206, 209],\n darkviolet: [148, 0, 211],\n deeppink: [255, 20, 147],\n deepskyblue: [0, 191, 255],\n dimgray: [105, 105, 105],\n dimgrey: [105, 105, 105],\n dodgerblue: [30, 144, 255],\n firebrick: [178, 34, 34],\n floralwhite: [255, 250, 240],\n forestgreen: [34, 139, 34],\n fuchsia: [255, 0, 255],\n gainsboro: [220, 220, 220],\n ghostwhite: [248, 248, 255],\n gold: [255, 215, 0],\n goldenrod: [218, 165, 32],\n gray: [128, 128, 128],\n green: [0, 128, 0],\n greenyellow: [173, 255, 47],\n grey: [128, 128, 128],\n honeydew: [240, 255, 240],\n hotpink: [255, 105, 180],\n indianred: [205, 92, 92],\n indigo: [75, 0, 130],\n ivory: [255, 255, 240],\n khaki: [240, 230, 140],\n lavender: [230, 230, 250],\n lavenderblush: [255, 240, 245],\n lawngreen: [124, 252, 0],\n lemonchiffon: [255, 250, 205],\n lightblue: [173, 216, 230],\n lightcoral: [240, 128, 128],\n lightcyan: [224, 255, 255],\n lightgoldenrodyellow: [250, 250, 210],\n lightgray: [211, 211, 211],\n lightgreen: [144, 238, 144],\n lightgrey: [211, 211, 211],\n lightpink: [255, 182, 193],\n lightsalmon: [255, 160, 122],\n lightseagreen: [32, 178, 170],\n lightskyblue: [135, 206, 250],\n lightslategray: [119, 136, 153],\n lightslategrey: [119, 136, 153],\n lightsteelblue: [176, 196, 222],\n lightyellow: [255, 255, 224],\n lime: [0, 255, 0],\n limegreen: [50, 205, 50],\n linen: [250, 240, 230],\n magenta: [255, 0, 255],\n maroon: [128, 0, 0],\n mediumaquamarine: [102, 205, 170],\n mediumblue: [0, 0, 205],\n mediumorchid: [186, 85, 211],\n mediumpurple: [147, 112, 219],\n mediumseagreen: [60, 179, 113],\n mediumslateblue: [123, 104, 238],\n mediumspringgreen: [0, 250, 154],\n mediumturquoise: [72, 209, 204],\n mediumvioletred: [199, 21, 133],\n midnightblue: [25, 25, 112],\n mintcream: [245, 255, 250],\n mistyrose: [255, 228, 225],\n moccasin: [255, 228, 181],\n navajowhite: [255, 222, 173],\n navy: [0, 0, 128],\n oldlace: [253, 245, 230],\n olive: [128, 128, 0],\n olivedrab: [107, 142, 35],\n orange: [255, 165, 0],\n orangered: [255, 69, 0],\n orchid: [218, 112, 214],\n palegoldenrod: [238, 232, 170],\n palegreen: [152, 251, 152],\n paleturquoise: [175, 238, 238],\n palevioletred: [219, 112, 147],\n papayawhip: [255, 239, 213],\n peachpuff: [255, 218, 185],\n peru: [205, 133, 63],\n pink: [255, 192, 203],\n plum: [221, 160, 221],\n powderblue: [176, 224, 230],\n purple: [128, 0, 128],\n rebeccapurple: [102, 51, 153],\n red: [255, 0, 0],\n rosybrown: [188, 143, 143],\n royalblue: [65, 105, 225],\n saddlebrown: [139, 69, 19],\n salmon: [250, 128, 114],\n sandybrown: [244, 164, 96],\n seagreen: [46, 139, 87],\n seashell: [255, 245, 238],\n sienna: [160, 82, 45],\n silver: [192, 192, 192],\n skyblue: [135, 206, 235],\n slateblue: [106, 90, 205],\n slategray: [112, 128, 144],\n slategrey: [112, 128, 144],\n snow: [255, 250, 250],\n springgreen: [0, 255, 127],\n steelblue: [70, 130, 180],\n tan: [210, 180, 140],\n teal: [0, 128, 128],\n thistle: [216, 191, 216],\n tomato: [255, 99, 71],\n turquoise: [64, 224, 208],\n violet: [238, 130, 238],\n wheat: [245, 222, 179],\n white: [255, 255, 255],\n whitesmoke: [245, 245, 245],\n yellow: [255, 255, 0],\n yellowgreen: [154, 205, 50],\n};\n\n/**\n * Color representation used by WebGL.\n * Defined in sRGB color space and pre-blended with alpha.\n * @private\n */\nclass Color {\n /**\n * @param r Red component premultiplied by `alpha` 0..1\n * @param g Green component premultiplied by `alpha` 0..1\n * @param b Blue component premultiplied by `alpha` 0..1\n * @param [alpha=1] Alpha component 0..1\n * @param [premultiplied=true] Whether the `r`, `g` and `b` values have already\n * been multiplied by alpha. If `true` nothing happens if `false` then they will\n * be multiplied automatically.\n */\n constructor(r, g, b, alpha = 1, premultiplied = true) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = alpha;\n if (!premultiplied) {\n this.r *= alpha;\n this.g *= alpha;\n this.b *= alpha;\n if (!alpha) {\n // alpha = 0 erases completely rgb channels. This behavior is not desirable\n // if this particular color is later used in color interpolation.\n // Because of that, a reference to original color is saved.\n this.overwriteGetter('rgb', [r, g, b, alpha]);\n }\n }\n }\n /**\n * Parses CSS color strings and converts colors to sRGB color space if needed.\n * Officially supported color formats:\n * - keyword, e.g. 'aquamarine' or 'steelblue'\n * - hex (with 3, 4, 6 or 8 digits), e.g. '#f0f' or '#e9bebea9'\n * - rgb and rgba, e.g. 'rgb(0,240,120)' or 'rgba(0%,94%,47%,0.1)' or 'rgb(0 240 120 / .3)'\n * - hsl and hsla, e.g. 'hsl(0,0%,83%)' or 'hsla(0,0%,83%,.5)' or 'hsl(0 0% 83% / 20%)'\n *\n * @param input CSS color string to parse.\n * @returns A `Color` instance, or `undefined` if the input is not a valid color string.\n */\n static parse(input) {\n // in zoom-and-property function input could be an instance of Color class\n if (input instanceof Color) {\n return input;\n }\n if (typeof input !== 'string') {\n return;\n }\n const rgba = parseCssColor(input);\n if (rgba) {\n return new Color(...rgba, false);\n }\n }\n /**\n * Used in color interpolation and by 'to-rgba' expression.\n *\n * @returns Gien color, with reversed alpha blending, in sRGB color space.\n */\n get rgb() {\n const { r, g, b, a } = this;\n const f = a || Infinity; // reverse alpha blending factor\n return this.overwriteGetter('rgb', [r / f, g / f, b / f, a]);\n }\n /**\n * Used in color interpolation.\n *\n * @returns Gien color, with reversed alpha blending, in HCL color space.\n */\n get hcl() {\n return this.overwriteGetter('hcl', rgbToHcl(this.rgb));\n }\n /**\n * Used in color interpolation.\n *\n * @returns Gien color, with reversed alpha blending, in LAB color space.\n */\n get lab() {\n return this.overwriteGetter('lab', rgbToLab(this.rgb));\n }\n /**\n * Lazy getter pattern. When getter is called for the first time lazy value\n * is calculated and then overwrites getter function in given object instance.\n *\n * @example:\n * const redColor = Color.parse('red');\n * let x = redColor.hcl; // this will invoke `get hcl()`, which will calculate\n * // the value of red in HCL space and invoke this `overwriteGetter` function\n * // which in turn will set a field with a key 'hcl' in the `redColor` object.\n * // In other words it will override `get hcl()` from its `Color` prototype\n * // with its own property: hcl = [calculated red value in hcl].\n * let y = redColor.hcl; // next call will no longer invoke getter but simply\n * // return the previously calculated value\n * x === y; // true - `x` is exactly the same object as `y`\n *\n * @param getterKey Getter key\n * @param lazyValue Lazily calculated value to be memoized by current instance\n * @private\n */\n overwriteGetter(getterKey, lazyValue) {\n Object.defineProperty(this, getterKey, { value: lazyValue });\n return lazyValue;\n }\n /**\n * Used by 'to-string' expression.\n *\n * @returns Serialized color in format `rgba(r,g,b,a)`\n * where r,g,b are numbers within 0..255 and alpha is number within 1..0\n *\n * @example\n * var purple = new Color.parse('purple');\n * purple.toString; // = \"rgba(128,0,128,1)\"\n * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');\n * translucentGreen.toString(); // = \"rgba(26,207,26,0.73)\"\n */\n toString() {\n const [r, g, b, a] = this.rgb;\n return `rgba(${[r, g, b].map(n => Math.round(n * 255)).join(',')},${a})`;\n }\n}\nColor.black = new Color(0, 0, 0, 1);\nColor.white = new Color(1, 1, 1, 1);\nColor.transparent = new Color(0, 0, 0, 0);\nColor.red = new Color(1, 0, 0, 1);\n\n// Flow type declarations for Intl cribbed from\n// https://github.com/facebook/flow/issues/1270\nclass Collator {\n constructor(caseSensitive, diacriticSensitive, locale) {\n if (caseSensitive)\n this.sensitivity = diacriticSensitive ? 'variant' : 'case';\n else\n this.sensitivity = diacriticSensitive ? 'accent' : 'base';\n this.locale = locale;\n this.collator = new Intl.Collator(this.locale ? this.locale : [], { sensitivity: this.sensitivity, usage: 'search' });\n }\n compare(lhs, rhs) {\n return this.collator.compare(lhs, rhs);\n }\n resolvedLocale() {\n // We create a Collator without \"usage: search\" because we don't want\n // the search options encoded in our result (e.g. \"en-u-co-search\")\n return new Intl.Collator(this.locale ? this.locale : [])\n .resolvedOptions().locale;\n }\n}\n\nclass FormattedSection {\n constructor(text, image, scale, fontStack, textColor) {\n this.text = text;\n this.image = image;\n this.scale = scale;\n this.fontStack = fontStack;\n this.textColor = textColor;\n }\n}\nclass Formatted {\n constructor(sections) {\n this.sections = sections;\n }\n static fromString(unformatted) {\n return new Formatted([new FormattedSection(unformatted, null, null, null, null)]);\n }\n isEmpty() {\n if (this.sections.length === 0)\n return true;\n return !this.sections.some(section => section.text.length !== 0 ||\n (section.image && section.image.name.length !== 0));\n }\n static factory(text) {\n if (text instanceof Formatted) {\n return text;\n }\n else {\n return Formatted.fromString(text);\n }\n }\n toString() {\n if (this.sections.length === 0)\n return '';\n return this.sections.map(section => section.text).join('');\n }\n}\n\n/**\n * A set of four numbers representing padding around a box. Create instances from\n * bare arrays or numeric values using the static method `Padding.parse`.\n * @private\n */\nclass Padding {\n constructor(values) {\n this.values = values.slice();\n }\n /**\n * Numeric padding values\n * @param input A padding value\n * @returns A `Padding` instance, or `undefined` if the input is not a valid padding value.\n */\n static parse(input) {\n if (input instanceof Padding) {\n return input;\n }\n // Backwards compatibility: bare number is treated the same as array with single value.\n // Padding applies to all four sides.\n if (typeof input === 'number') {\n return new Padding([input, input, input, input]);\n }\n if (!Array.isArray(input)) {\n return undefined;\n }\n if (input.length < 1 || input.length > 4) {\n return undefined;\n }\n for (const val of input) {\n if (typeof val !== 'number') {\n return undefined;\n }\n }\n // Expand shortcut properties into explicit 4-sided values\n switch (input.length) {\n case 1:\n input = [input[0], input[0], input[0], input[0]];\n break;\n case 2:\n input = [input[0], input[1], input[0], input[1]];\n break;\n case 3:\n input = [input[0], input[1], input[2], input[1]];\n break;\n }\n return new Padding(input);\n }\n toString() {\n return JSON.stringify(this.values);\n }\n}\n\n/** Set of valid anchor positions, as a set for validation */\nconst anchors = new Set(['center', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right']);\n/**\n * Utility class to assist managing values for text-variable-anchor-offset property. Create instances from\n * bare arrays using the static method `VariableAnchorOffsetCollection.parse`.\n * @private\n */\nclass VariableAnchorOffsetCollection {\n constructor(values) {\n this.values = values.slice();\n }\n static parse(input) {\n if (input instanceof VariableAnchorOffsetCollection) {\n return input;\n }\n if (!Array.isArray(input) ||\n input.length < 1 ||\n input.length % 2 !== 0) {\n return undefined;\n }\n for (let i = 0; i < input.length; i += 2) {\n // Elements in even positions should be anchor positions; Elements in odd positions should be offset values\n const anchorValue = input[i];\n const offsetValue = input[i + 1];\n if (typeof anchorValue !== 'string' || !anchors.has(anchorValue)) {\n return undefined;\n }\n if (!Array.isArray(offsetValue) || offsetValue.length !== 2 || typeof offsetValue[0] !== 'number' || typeof offsetValue[1] !== 'number') {\n return undefined;\n }\n }\n return new VariableAnchorOffsetCollection(input);\n }\n toString() {\n return JSON.stringify(this.values);\n }\n}\n\nclass ResolvedImage {\n constructor(options) {\n this.name = options.name;\n this.available = options.available;\n }\n toString() {\n return this.name;\n }\n static fromString(name) {\n if (!name)\n return null; // treat empty values as no image\n return new ResolvedImage({ name, available: false });\n }\n}\n\nfunction validateRGBA(r, g, b, a) {\n if (!(typeof r === 'number' && r >= 0 && r <= 255 &&\n typeof g === 'number' && g >= 0 && g <= 255 &&\n typeof b === 'number' && b >= 0 && b <= 255)) {\n const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b];\n return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`;\n }\n if (!(typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1))) {\n return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`;\n }\n return null;\n}\nfunction isValue(mixed) {\n if (mixed === null ||\n typeof mixed === 'string' ||\n typeof mixed === 'boolean' ||\n typeof mixed === 'number' ||\n mixed instanceof Color ||\n mixed instanceof Collator ||\n mixed instanceof Formatted ||\n mixed instanceof Padding ||\n mixed instanceof VariableAnchorOffsetCollection ||\n mixed instanceof ResolvedImage) {\n return true;\n }\n else if (Array.isArray(mixed)) {\n for (const item of mixed) {\n if (!isValue(item)) {\n return false;\n }\n }\n return true;\n }\n else if (typeof mixed === 'object') {\n for (const key in mixed) {\n if (!isValue(mixed[key])) {\n return false;\n }\n }\n return true;\n }\n else {\n return false;\n }\n}\nfunction typeOf(value) {\n if (value === null) {\n return NullType;\n }\n else if (typeof value === 'string') {\n return StringType;\n }\n else if (typeof value === 'boolean') {\n return BooleanType;\n }\n else if (typeof value === 'number') {\n return NumberType;\n }\n else if (value instanceof Color) {\n return ColorType;\n }\n else if (value instanceof Collator) {\n return CollatorType;\n }\n else if (value instanceof Formatted) {\n return FormattedType;\n }\n else if (value instanceof Padding) {\n return PaddingType;\n }\n else if (value instanceof VariableAnchorOffsetCollection) {\n return VariableAnchorOffsetCollectionType;\n }\n else if (value instanceof ResolvedImage) {\n return ResolvedImageType;\n }\n else if (Array.isArray(value)) {\n const length = value.length;\n let itemType;\n for (const item of value) {\n const t = typeOf(item);\n if (!itemType) {\n itemType = t;\n }\n else if (itemType === t) {\n continue;\n }\n else {\n itemType = ValueType;\n break;\n }\n }\n return array$1(itemType || ValueType, length);\n }\n else {\n return ObjectType;\n }\n}\nfunction toString(value) {\n const type = typeof value;\n if (value === null) {\n return '';\n }\n else if (type === 'string' || type === 'number' || type === 'boolean') {\n return String(value);\n }\n else if (value instanceof Color || value instanceof Formatted || value instanceof Padding || value instanceof VariableAnchorOffsetCollection || value instanceof ResolvedImage) {\n return value.toString();\n }\n else {\n return JSON.stringify(value);\n }\n}\n\nclass Literal {\n constructor(type, value) {\n this.type = type;\n this.value = value;\n }\n static parse(args, context) {\n if (args.length !== 2)\n return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n if (!isValue(args[1]))\n return context.error('invalid value');\n const value = args[1];\n let type = typeOf(value);\n // special case: infer the item type if possible for zero-length arrays\n const expected = context.expectedType;\n if (type.kind === 'array' &&\n type.N === 0 &&\n expected &&\n expected.kind === 'array' &&\n (typeof expected.N !== 'number' || expected.N === 0)) {\n type = expected;\n }\n return new Literal(type, value);\n }\n evaluate() {\n return this.value;\n }\n eachChild() { }\n outputDefined() {\n return true;\n }\n}\n\nclass RuntimeError {\n constructor(message) {\n this.name = 'ExpressionEvaluationError';\n this.message = message;\n }\n toJSON() {\n return this.message;\n }\n}\n\nconst types$1 = {\n string: StringType,\n number: NumberType,\n boolean: BooleanType,\n object: ObjectType\n};\nclass Assertion {\n constructor(type, args) {\n this.type = type;\n this.args = args;\n }\n static parse(args, context) {\n if (args.length < 2)\n return context.error('Expected at least one argument.');\n let i = 1;\n let type;\n const name = args[0];\n if (name === 'array') {\n let itemType;\n if (args.length > 2) {\n const type = args[1];\n if (typeof type !== 'string' || !(type in types$1) || type === 'object')\n return context.error('The item type argument of \"array\" must be one of string, number, boolean', 1);\n itemType = types$1[type];\n i++;\n }\n else {\n itemType = ValueType;\n }\n let N;\n if (args.length > 3) {\n if (args[2] !== null &&\n (typeof args[2] !== 'number' ||\n args[2] < 0 ||\n args[2] !== Math.floor(args[2]))) {\n return context.error('The length argument to \"array\" must be a positive integer literal', 2);\n }\n N = args[2];\n i++;\n }\n type = array$1(itemType, N);\n }\n else {\n if (!types$1[name])\n throw new Error(`Types doesn't contain name = ${name}`);\n type = types$1[name];\n }\n const parsed = [];\n for (; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input)\n return null;\n parsed.push(input);\n }\n return new Assertion(type, parsed);\n }\n evaluate(ctx) {\n for (let i = 0; i < this.args.length; i++) {\n const value = this.args[i].evaluate(ctx);\n const error = checkSubtype(this.type, typeOf(value));\n if (!error) {\n return value;\n }\n else if (i === this.args.length - 1) {\n throw new RuntimeError(`Expected value to be of type ${toString$1(this.type)}, but found ${toString$1(typeOf(value))} instead.`);\n }\n }\n throw new Error();\n }\n eachChild(fn) {\n this.args.forEach(fn);\n }\n outputDefined() {\n return this.args.every(arg => arg.outputDefined());\n }\n}\n\nconst types = {\n 'to-boolean': BooleanType,\n 'to-color': ColorType,\n 'to-number': NumberType,\n 'to-string': StringType\n};\n/**\n * Special form for error-coalescing coercion expressions \"to-number\",\n * \"to-color\". Since these coercions can fail at runtime, they accept multiple\n * arguments, only evaluating one at a time until one succeeds.\n *\n * @private\n */\nclass Coercion {\n constructor(type, args) {\n this.type = type;\n this.args = args;\n }\n static parse(args, context) {\n if (args.length < 2)\n return context.error('Expected at least one argument.');\n const name = args[0];\n if (!types[name])\n throw new Error(`Can't parse ${name} as it is not part of the known types`);\n if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2)\n return context.error('Expected one argument.');\n const type = types[name];\n const parsed = [];\n for (let i = 1; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input)\n return null;\n parsed.push(input);\n }\n return new Coercion(type, parsed);\n }\n evaluate(ctx) {\n switch (this.type.kind) {\n case 'boolean':\n return Boolean(this.args[0].evaluate(ctx));\n case 'color': {\n let input;\n let error;\n for (const arg of this.args) {\n input = arg.evaluate(ctx);\n error = null;\n if (input instanceof Color) {\n return input;\n }\n else if (typeof input === 'string') {\n const c = ctx.parseColor(input);\n if (c)\n return c;\n }\n else if (Array.isArray(input)) {\n if (input.length < 3 || input.length > 4) {\n error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`;\n }\n else {\n error = validateRGBA(input[0], input[1], input[2], input[3]);\n }\n if (!error) {\n return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]);\n }\n }\n }\n throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`);\n }\n case 'padding': {\n let input;\n for (const arg of this.args) {\n input = arg.evaluate(ctx);\n const pad = Padding.parse(input);\n if (pad) {\n return pad;\n }\n }\n throw new RuntimeError(`Could not parse padding from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`);\n }\n case 'variableAnchorOffsetCollection': {\n let input;\n for (const arg of this.args) {\n input = arg.evaluate(ctx);\n const coll = VariableAnchorOffsetCollection.parse(input);\n if (coll) {\n return coll;\n }\n }\n throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`);\n }\n case 'number': {\n let value = null;\n for (const arg of this.args) {\n value = arg.evaluate(ctx);\n if (value === null)\n return 0;\n const num = Number(value);\n if (isNaN(num))\n continue;\n return num;\n }\n throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`);\n }\n case 'formatted':\n // There is no explicit 'to-formatted' but this coercion can be implicitly\n // created by properties that expect the 'formatted' type.\n return Formatted.fromString(toString(this.args[0].evaluate(ctx)));\n case 'resolvedImage':\n return ResolvedImage.fromString(toString(this.args[0].evaluate(ctx)));\n default:\n return toString(this.args[0].evaluate(ctx));\n }\n }\n eachChild(fn) {\n this.args.forEach(fn);\n }\n outputDefined() {\n return this.args.every(arg => arg.outputDefined());\n }\n}\n\nconst geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon'];\nclass EvaluationContext {\n constructor() {\n this.globals = null;\n this.feature = null;\n this.featureState = null;\n this.formattedSection = null;\n this._parseColorCache = {};\n this.availableImages = null;\n this.canonical = null;\n }\n id() {\n return this.feature && 'id' in this.feature ? this.feature.id : null;\n }\n geometryType() {\n return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null;\n }\n geometry() {\n return this.feature && 'geometry' in this.feature ? this.feature.geometry : null;\n }\n canonicalID() {\n return this.canonical;\n }\n properties() {\n return this.feature && this.feature.properties || {};\n }\n parseColor(input) {\n let cached = this._parseColorCache[input];\n if (!cached) {\n cached = this._parseColorCache[input] = Color.parse(input);\n }\n return cached;\n }\n}\n\n/**\n * State associated parsing at a given point in an expression tree.\n * @private\n */\nclass ParsingContext {\n constructor(registry, isConstantFunc, path = [], expectedType, scope = new Scope(), errors = []) {\n this.registry = registry;\n this.path = path;\n this.key = path.map(part => `[${part}]`).join('');\n this.scope = scope;\n this.errors = errors;\n this.expectedType = expectedType;\n this._isConstant = isConstantFunc;\n }\n /**\n * @param expr the JSON expression to parse\n * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed\n * @param options\n * @param options.omitTypeAnnotations set true to omit inferred type annotations. Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation.\n * @private\n */\n parse(expr, index, expectedType, bindings, options = {}) {\n if (index) {\n return this.concat(index, expectedType, bindings)._parse(expr, options);\n }\n return this._parse(expr, options);\n }\n _parse(expr, options) {\n if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') {\n expr = ['literal', expr];\n }\n function annotate(parsed, type, typeAnnotation) {\n if (typeAnnotation === 'assert') {\n return new Assertion(type, [parsed]);\n }\n else if (typeAnnotation === 'coerce') {\n return new Coercion(type, [parsed]);\n }\n else {\n return parsed;\n }\n }\n if (Array.isArray(expr)) {\n if (expr.length === 0) {\n return this.error('Expected an array with at least one element. If you wanted a literal array, use [\"literal\", []].');\n }\n const op = expr[0];\n if (typeof op !== 'string') {\n this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use [\"literal\", [...]].`, 0);\n return null;\n }\n const Expr = this.registry[op];\n if (Expr) {\n let parsed = Expr.parse(expr, this);\n if (!parsed)\n return null;\n if (this.expectedType) {\n const expected = this.expectedType;\n const actual = parsed.type;\n // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion.\n // When we expect a color or formatted string, but have a string or value, wrap it in a coercion.\n // Otherwise, we do static type-checking.\n //\n // These behaviors are overridable for:\n // * The \"coalesce\" operator, which needs to omit type annotations.\n // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion.\n //\n if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'assert');\n }\n else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');\n }\n else if (expected.kind === 'padding' && (actual.kind === 'value' || actual.kind === 'number' || actual.kind === 'array')) {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');\n }\n else if (expected.kind === 'variableAnchorOffsetCollection' && (actual.kind === 'value' || actual.kind === 'array')) {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');\n }\n else if (this.checkSubtype(expected, actual)) {\n return null;\n }\n }\n // If an expression's arguments are all literals, we can evaluate\n // it immediately and replace it with a literal value in the\n // parsed/compiled result. Expressions that expect an image should\n // not be resolved here so we can later get the available images.\n if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && this._isConstant(parsed)) {\n const ec = new EvaluationContext();\n try {\n parsed = new Literal(parsed.type, parsed.evaluate(ec));\n }\n catch (e) {\n this.error(e.message);\n return null;\n }\n }\n return parsed;\n }\n return this.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n }\n else if (typeof expr === 'undefined') {\n return this.error('\\'undefined\\' value invalid. Use null instead.');\n }\n else if (typeof expr === 'object') {\n return this.error('Bare objects invalid. Use [\"literal\", {...}] instead.');\n }\n else {\n return this.error(`Expected an array, but found ${typeof expr} instead.`);\n }\n }\n /**\n * Returns a copy of this context suitable for parsing the subexpression at\n * index `index`, optionally appending to 'let' binding map.\n *\n * Note that `errors` property, intended for collecting errors while\n * parsing, is copied by reference rather than cloned.\n * @private\n */\n concat(index, expectedType, bindings) {\n const path = typeof index === 'number' ? this.path.concat(index) : this.path;\n const scope = bindings ? this.scope.concat(bindings) : this.scope;\n return new ParsingContext(this.registry, this._isConstant, path, expectedType || null, scope, this.errors);\n }\n /**\n * Push a parsing (or type checking) error into the `this.errors`\n * @param error The message\n * @param keys Optionally specify the source of the error at a child\n * of the current expression at `this.key`.\n * @private\n */\n error(error, ...keys) {\n const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`;\n this.errors.push(new ExpressionParsingError(key, error));\n }\n /**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message and also pushes it to `this.errors`.\n * @param expected The expected type\n * @param t The actual type\n * @returns null if `t` is a subtype of `expected`; otherwise returns an error message\n */\n checkSubtype(expected, t) {\n const error = checkSubtype(expected, t);\n if (error)\n this.error(error);\n return error;\n }\n}\n\nclass Let {\n constructor(bindings, result) {\n this.type = result.type;\n this.bindings = [].concat(bindings);\n this.result = result;\n }\n evaluate(ctx) {\n return this.result.evaluate(ctx);\n }\n eachChild(fn) {\n for (const binding of this.bindings) {\n fn(binding[1]);\n }\n fn(this.result);\n }\n static parse(args, context) {\n if (args.length < 4)\n return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`);\n const bindings = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const name = args[i];\n if (typeof name !== 'string') {\n return context.error(`Expected string, but found ${typeof name} instead.`, i);\n }\n if (/[^a-zA-Z0-9_]/.test(name)) {\n return context.error('Variable names must contain only alphanumeric characters or \\'_\\'.', i);\n }\n const value = context.parse(args[i + 1], i + 1);\n if (!value)\n return null;\n bindings.push([name, value]);\n }\n const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings);\n if (!result)\n return null;\n return new Let(bindings, result);\n }\n outputDefined() {\n return this.result.outputDefined();\n }\n}\n\nclass Var {\n constructor(name, boundExpression) {\n this.type = boundExpression.type;\n this.name = name;\n this.boundExpression = boundExpression;\n }\n static parse(args, context) {\n if (args.length !== 2 || typeof args[1] !== 'string')\n return context.error('\\'var\\' expression requires exactly one string literal argument.');\n const name = args[1];\n if (!context.scope.has(name)) {\n return context.error(`Unknown variable \"${name}\". Make sure \"${name}\" has been bound in an enclosing \"let\" expression before using it.`, 1);\n }\n return new Var(name, context.scope.get(name));\n }\n evaluate(ctx) {\n return this.boundExpression.evaluate(ctx);\n }\n eachChild() { }\n outputDefined() {\n return false;\n }\n}\n\nclass At {\n constructor(type, index, input) {\n this.type = type;\n this.index = index;\n this.input = input;\n }\n static parse(args, context) {\n if (args.length !== 3)\n return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n const index = context.parse(args[1], 1, NumberType);\n const input = context.parse(args[2], 2, array$1(context.expectedType || ValueType));\n if (!index || !input)\n return null;\n const t = input.type;\n return new At(t.itemType, index, input);\n }\n evaluate(ctx) {\n const index = this.index.evaluate(ctx);\n const array = this.input.evaluate(ctx);\n if (index < 0) {\n throw new RuntimeError(`Array index out of bounds: ${index} < 0.`);\n }\n if (index >= array.length) {\n throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`);\n }\n if (index !== Math.floor(index)) {\n throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`);\n }\n return array[index];\n }\n eachChild(fn) {\n fn(this.index);\n fn(this.input);\n }\n outputDefined() {\n return false;\n }\n}\n\nclass In {\n constructor(needle, haystack) {\n this.type = BooleanType;\n this.needle = needle;\n this.haystack = haystack;\n }\n static parse(args, context) {\n if (args.length !== 3) {\n return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n }\n const needle = context.parse(args[1], 1, ValueType);\n const haystack = context.parse(args[2], 2, ValueType);\n if (!needle || !haystack)\n return null;\n if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {\n return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`);\n }\n return new In(needle, haystack);\n }\n evaluate(ctx) {\n const needle = this.needle.evaluate(ctx);\n const haystack = this.haystack.evaluate(ctx);\n if (!haystack)\n return false;\n if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {\n throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`);\n }\n if (!isValidNativeType(haystack, ['string', 'array'])) {\n throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`);\n }\n return haystack.indexOf(needle) >= 0;\n }\n eachChild(fn) {\n fn(this.needle);\n fn(this.haystack);\n }\n outputDefined() {\n return true;\n }\n}\n\nclass IndexOf {\n constructor(needle, haystack, fromIndex) {\n this.type = NumberType;\n this.needle = needle;\n this.haystack = haystack;\n this.fromIndex = fromIndex;\n }\n static parse(args, context) {\n if (args.length <= 2 || args.length >= 5) {\n return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);\n }\n const needle = context.parse(args[1], 1, ValueType);\n const haystack = context.parse(args[2], 2, ValueType);\n if (!needle || !haystack)\n return null;\n if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {\n return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`);\n }\n if (args.length === 4) {\n const fromIndex = context.parse(args[3], 3, NumberType);\n if (!fromIndex)\n return null;\n return new IndexOf(needle, haystack, fromIndex);\n }\n else {\n return new IndexOf(needle, haystack);\n }\n }\n evaluate(ctx) {\n const needle = this.needle.evaluate(ctx);\n const haystack = this.haystack.evaluate(ctx);\n if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {\n throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`);\n }\n let fromIndex;\n if (this.fromIndex) {\n fromIndex = this.fromIndex.evaluate(ctx);\n }\n if (isValidNativeType(haystack, ['string'])) {\n const rawIndex = haystack.indexOf(needle, fromIndex);\n if (rawIndex === -1) {\n return -1;\n }\n else {\n // The index may be affected by surrogate pairs, so get the length of the preceding substring.\n return [...haystack.slice(0, rawIndex)].length;\n }\n }\n else if (isValidNativeType(haystack, ['array'])) {\n return haystack.indexOf(needle, fromIndex);\n }\n else {\n throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`);\n }\n }\n eachChild(fn) {\n fn(this.needle);\n fn(this.haystack);\n if (this.fromIndex) {\n fn(this.fromIndex);\n }\n }\n outputDefined() {\n return false;\n }\n}\n\nclass Match {\n constructor(inputType, outputType, input, cases, outputs, otherwise) {\n this.inputType = inputType;\n this.type = outputType;\n this.input = input;\n this.cases = cases;\n this.outputs = outputs;\n this.otherwise = otherwise;\n }\n static parse(args, context) {\n if (args.length < 5)\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n if (args.length % 2 !== 1)\n return context.error('Expected an even number of arguments.');\n let inputType;\n let outputType;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n const cases = {};\n const outputs = [];\n for (let i = 2; i < args.length - 1; i += 2) {\n let labels = args[i];\n const value = args[i + 1];\n if (!Array.isArray(labels)) {\n labels = [labels];\n }\n const labelContext = context.concat(i);\n if (labels.length === 0) {\n return labelContext.error('Expected at least one branch label.');\n }\n for (const label of labels) {\n if (typeof label !== 'number' && typeof label !== 'string') {\n return labelContext.error('Branch labels must be numbers or strings.');\n }\n else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) {\n return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);\n }\n else if (typeof label === 'number' && Math.floor(label) !== label) {\n return labelContext.error('Numeric branch labels must be integer values.');\n }\n else if (!inputType) {\n inputType = typeOf(label);\n }\n else if (labelContext.checkSubtype(inputType, typeOf(label))) {\n return null;\n }\n if (typeof cases[String(label)] !== 'undefined') {\n return labelContext.error('Branch labels must be unique.');\n }\n cases[String(label)] = outputs.length;\n }\n const result = context.parse(value, i, outputType);\n if (!result)\n return null;\n outputType = outputType || result.type;\n outputs.push(result);\n }\n const input = context.parse(args[1], 1, ValueType);\n if (!input)\n return null;\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise)\n return null;\n if (input.type.kind !== 'value' && context.concat(1).checkSubtype(inputType, input.type)) {\n return null;\n }\n return new Match(inputType, outputType, input, cases, outputs, otherwise);\n }\n evaluate(ctx) {\n const input = this.input.evaluate(ctx);\n const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise;\n return output.evaluate(ctx);\n }\n eachChild(fn) {\n fn(this.input);\n this.outputs.forEach(fn);\n fn(this.otherwise);\n }\n outputDefined() {\n return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined();\n }\n}\n\nclass Case {\n constructor(type, branches, otherwise) {\n this.type = type;\n this.branches = branches;\n this.otherwise = otherwise;\n }\n static parse(args, context) {\n if (args.length < 4)\n return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`);\n if (args.length % 2 !== 0)\n return context.error('Expected an odd number of arguments.');\n let outputType;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n const branches = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const test = context.parse(args[i], i, BooleanType);\n if (!test)\n return null;\n const result = context.parse(args[i + 1], i + 1, outputType);\n if (!result)\n return null;\n branches.push([test, result]);\n outputType = outputType || result.type;\n }\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise)\n return null;\n if (!outputType)\n throw new Error('Can\\'t infer output type');\n return new Case(outputType, branches, otherwise);\n }\n evaluate(ctx) {\n for (const [test, expression] of this.branches) {\n if (test.evaluate(ctx)) {\n return expression.evaluate(ctx);\n }\n }\n return this.otherwise.evaluate(ctx);\n }\n eachChild(fn) {\n for (const [test, expression] of this.branches) {\n fn(test);\n fn(expression);\n }\n fn(this.otherwise);\n }\n outputDefined() {\n return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined();\n }\n}\n\nclass Slice {\n constructor(type, input, beginIndex, endIndex) {\n this.type = type;\n this.input = input;\n this.beginIndex = beginIndex;\n this.endIndex = endIndex;\n }\n static parse(args, context) {\n if (args.length <= 2 || args.length >= 5) {\n return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);\n }\n const input = context.parse(args[1], 1, ValueType);\n const beginIndex = context.parse(args[2], 2, NumberType);\n if (!input || !beginIndex)\n return null;\n if (!isValidType(input.type, [array$1(ValueType), StringType, ValueType])) {\n return context.error(`Expected first argument to be of type array or string, but found ${toString$1(input.type)} instead`);\n }\n if (args.length === 4) {\n const endIndex = context.parse(args[3], 3, NumberType);\n if (!endIndex)\n return null;\n return new Slice(input.type, input, beginIndex, endIndex);\n }\n else {\n return new Slice(input.type, input, beginIndex);\n }\n }\n evaluate(ctx) {\n const input = this.input.evaluate(ctx);\n const beginIndex = this.beginIndex.evaluate(ctx);\n let endIndex;\n if (this.endIndex) {\n endIndex = this.endIndex.evaluate(ctx);\n }\n if (isValidNativeType(input, ['string'])) {\n // Indices may be affected by surrogate pairs.\n return [...input].slice(beginIndex, endIndex).join('');\n }\n else if (isValidNativeType(input, ['array'])) {\n return input.slice(beginIndex, endIndex);\n }\n else {\n throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString$1(typeOf(input))} instead.`);\n }\n }\n eachChild(fn) {\n fn(this.input);\n fn(this.beginIndex);\n if (this.endIndex) {\n fn(this.endIndex);\n }\n }\n outputDefined() {\n return false;\n }\n}\n\n/**\n * Returns the index of the last stop <= input, or 0 if it doesn't exist.\n * @private\n */\nfunction findStopLessThanOrEqualTo(stops, input) {\n const lastIndex = stops.length - 1;\n let lowerIndex = 0;\n let upperIndex = lastIndex;\n let currentIndex = 0;\n let currentValue, nextValue;\n while (lowerIndex <= upperIndex) {\n currentIndex = Math.floor((lowerIndex + upperIndex) / 2);\n currentValue = stops[currentIndex];\n nextValue = stops[currentIndex + 1];\n if (currentValue <= input) {\n if (currentIndex === lastIndex || input < nextValue) { // Search complete\n return currentIndex;\n }\n lowerIndex = currentIndex + 1;\n }\n else if (currentValue > input) {\n upperIndex = currentIndex - 1;\n }\n else {\n throw new RuntimeError('Input is not a number.');\n }\n }\n return 0;\n}\n\nclass Step {\n constructor(type, input, stops) {\n this.type = type;\n this.input = input;\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n static parse(args, context) {\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n if ((args.length - 1) % 2 !== 0) {\n return context.error('Expected an even number of arguments.');\n }\n const input = context.parse(args[1], 1, NumberType);\n if (!input)\n return null;\n const stops = [];\n let outputType = null;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n for (let i = 1; i < args.length; i += 2) {\n const label = i === 1 ? -Infinity : args[i];\n const value = args[i + 1];\n const labelKey = i;\n const valueKey = i + 1;\n if (typeof label !== 'number') {\n return context.error('Input/output pairs for \"step\" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);\n }\n if (stops.length && stops[stops.length - 1][0] >= label) {\n return context.error('Input/output pairs for \"step\" expressions must be arranged with input values in strictly ascending order.', labelKey);\n }\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed)\n return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n return new Step(outputType, input, stops);\n }\n evaluate(ctx) {\n const labels = this.labels;\n const outputs = this.outputs;\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n const value = this.input.evaluate(ctx);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\n const index = findStopLessThanOrEqualTo(labels, value);\n return outputs[index].evaluate(ctx);\n }\n eachChild(fn) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n outputDefined() {\n return this.outputs.every(out => out.outputDefined());\n }\n}\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar unitbezier = UnitBezier;\n\nfunction UnitBezier(p1x, p1y, p2x, p2y) {\n // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).\n this.cx = 3.0 * p1x;\n this.bx = 3.0 * (p2x - p1x) - this.cx;\n this.ax = 1.0 - this.cx - this.bx;\n\n this.cy = 3.0 * p1y;\n this.by = 3.0 * (p2y - p1y) - this.cy;\n this.ay = 1.0 - this.cy - this.by;\n\n this.p1x = p1x;\n this.p1y = p1y;\n this.p2x = p2x;\n this.p2y = p2y;\n}\n\nUnitBezier.prototype = {\n sampleCurveX: function (t) {\n // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.\n return ((this.ax * t + this.bx) * t + this.cx) * t;\n },\n\n sampleCurveY: function (t) {\n return ((this.ay * t + this.by) * t + this.cy) * t;\n },\n\n sampleCurveDerivativeX: function (t) {\n return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;\n },\n\n solveCurveX: function (x, epsilon) {\n if (epsilon === undefined) epsilon = 1e-6;\n\n if (x < 0.0) return 0.0;\n if (x > 1.0) return 1.0;\n\n var t = x;\n\n // First try a few iterations of Newton's method - normally very fast.\n for (var i = 0; i < 8; i++) {\n var x2 = this.sampleCurveX(t) - x;\n if (Math.abs(x2) < epsilon) return t;\n\n var d2 = this.sampleCurveDerivativeX(t);\n if (Math.abs(d2) < 1e-6) break;\n\n t = t - x2 / d2;\n }\n\n // Fall back to the bisection method for reliability.\n var t0 = 0.0;\n var t1 = 1.0;\n t = x;\n\n for (i = 0; i < 20; i++) {\n x2 = this.sampleCurveX(t);\n if (Math.abs(x2 - x) < epsilon) break;\n\n if (x > x2) {\n t0 = t;\n } else {\n t1 = t;\n }\n\n t = (t1 - t0) * 0.5 + t0;\n }\n\n return t;\n },\n\n solve: function (x, epsilon) {\n return this.sampleCurveY(this.solveCurveX(x, epsilon));\n }\n};\n\nvar UnitBezier$1 = /*@__PURE__*/getDefaultExportFromCjs(unitbezier);\n\n/**\n * Checks whether the specified color space is one of the supported interpolation color spaces.\n *\n * @param colorSpace Color space key to verify.\n * @returns `true` if the specified color space is one of the supported\n * interpolation color spaces, `false` otherwise\n */\nfunction isSupportedInterpolationColorSpace(colorSpace) {\n return colorSpace === 'rgb' || colorSpace === 'hcl' || colorSpace === 'lab';\n}\n/**\n * @param interpolationType Interpolation type\n * @returns interpolation fn\n * @deprecated use `interpolate[type]` instead\n */\nconst interpolateFactory = (interpolationType) => {\n switch (interpolationType) {\n case 'number': return number;\n case 'color': return color;\n case 'array': return array;\n case 'padding': return padding;\n case 'variableAnchorOffsetCollection': return variableAnchorOffsetCollection;\n }\n};\nfunction number(from, to, t) {\n return from + t * (to - from);\n}\nfunction color(from, to, t, spaceKey = 'rgb') {\n switch (spaceKey) {\n case 'rgb': {\n const [r, g, b, alpha] = array(from.rgb, to.rgb, t);\n return new Color(r, g, b, alpha, false);\n }\n case 'hcl': {\n const [hue0, chroma0, light0, alphaF] = from.hcl;\n const [hue1, chroma1, light1, alphaT] = to.hcl;\n // https://github.com/gka/chroma.js/blob/cd1b3c0926c7a85cbdc3b1453b3a94006de91a92/src/interpolator/_hsx.js\n let hue, chroma;\n if (!isNaN(hue0) && !isNaN(hue1)) {\n let dh = hue1 - hue0;\n if (hue1 > hue0 && dh > 180) {\n dh -= 360;\n }\n else if (hue1 < hue0 && hue0 - hue1 > 180) {\n dh += 360;\n }\n hue = hue0 + t * dh;\n }\n else if (!isNaN(hue0)) {\n hue = hue0;\n if (light1 === 1 || light1 === 0)\n chroma = chroma0;\n }\n else if (!isNaN(hue1)) {\n hue = hue1;\n if (light0 === 1 || light0 === 0)\n chroma = chroma1;\n }\n else {\n hue = NaN;\n }\n const [r, g, b, alpha] = hclToRgb([\n hue,\n chroma !== null && chroma !== void 0 ? chroma : number(chroma0, chroma1, t),\n number(light0, light1, t),\n number(alphaF, alphaT, t),\n ]);\n return new Color(r, g, b, alpha, false);\n }\n case 'lab': {\n const [r, g, b, alpha] = labToRgb(array(from.lab, to.lab, t));\n return new Color(r, g, b, alpha, false);\n }\n }\n}\nfunction array(from, to, t) {\n return from.map((d, i) => {\n return number(d, to[i], t);\n });\n}\nfunction padding(from, to, t) {\n return new Padding(array(from.values, to.values, t));\n}\nfunction variableAnchorOffsetCollection(from, to, t) {\n const fromValues = from.values;\n const toValues = to.values;\n if (fromValues.length !== toValues.length) {\n throw new RuntimeError(`Cannot interpolate values of different length. from: ${from.toString()}, to: ${to.toString()}`);\n }\n const output = [];\n for (let i = 0; i < fromValues.length; i += 2) {\n // Anchor entries must match\n if (fromValues[i] !== toValues[i]) {\n throw new RuntimeError(`Cannot interpolate values containing mismatched anchors. from[${i}]: ${fromValues[i]}, to[${i}]: ${toValues[i]}`);\n }\n output.push(fromValues[i]);\n // Interpolate the offset values for each anchor\n const [fx, fy] = fromValues[i + 1];\n const [tx, ty] = toValues[i + 1];\n output.push([number(fx, tx, t), number(fy, ty, t)]);\n }\n return new VariableAnchorOffsetCollection(output);\n}\nconst interpolate = {\n number,\n color,\n array,\n padding,\n variableAnchorOffsetCollection\n};\n\nclass Interpolate {\n constructor(type, operator, interpolation, input, stops) {\n this.type = type;\n this.operator = operator;\n this.interpolation = interpolation;\n this.input = input;\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n static interpolationFactor(interpolation, input, lower, upper) {\n let t = 0;\n if (interpolation.name === 'exponential') {\n t = exponentialInterpolation(input, interpolation.base, lower, upper);\n }\n else if (interpolation.name === 'linear') {\n t = exponentialInterpolation(input, 1, lower, upper);\n }\n else if (interpolation.name === 'cubic-bezier') {\n const c = interpolation.controlPoints;\n const ub = new UnitBezier$1(c[0], c[1], c[2], c[3]);\n t = ub.solve(exponentialInterpolation(input, 1, lower, upper));\n }\n return t;\n }\n static parse(args, context) {\n let [operator, interpolation, input, ...rest] = args;\n if (!Array.isArray(interpolation) || interpolation.length === 0) {\n return context.error('Expected an interpolation type expression.', 1);\n }\n if (interpolation[0] === 'linear') {\n interpolation = { name: 'linear' };\n }\n else if (interpolation[0] === 'exponential') {\n const base = interpolation[1];\n if (typeof base !== 'number')\n return context.error('Exponential interpolation requires a numeric base.', 1, 1);\n interpolation = {\n name: 'exponential',\n base\n };\n }\n else if (interpolation[0] === 'cubic-bezier') {\n const controlPoints = interpolation.slice(1);\n if (controlPoints.length !== 4 ||\n controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)) {\n return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1);\n }\n interpolation = {\n name: 'cubic-bezier',\n controlPoints: controlPoints\n };\n }\n else {\n return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0);\n }\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n if ((args.length - 1) % 2 !== 0) {\n return context.error('Expected an even number of arguments.');\n }\n input = context.parse(input, 2, NumberType);\n if (!input)\n return null;\n const stops = [];\n let outputType = null;\n if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') {\n outputType = ColorType;\n }\n else if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n for (let i = 0; i < rest.length; i += 2) {\n const label = rest[i];\n const value = rest[i + 1];\n const labelKey = i + 3;\n const valueKey = i + 4;\n if (typeof label !== 'number') {\n return context.error('Input/output pairs for \"interpolate\" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);\n }\n if (stops.length && stops[stops.length - 1][0] >= label) {\n return context.error('Input/output pairs for \"interpolate\" expressions must be arranged with input values in strictly ascending order.', labelKey);\n }\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed)\n return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n if (!verifyType(outputType, NumberType) &&\n !verifyType(outputType, ColorType) &&\n !verifyType(outputType, PaddingType) &&\n !verifyType(outputType, VariableAnchorOffsetCollectionType) &&\n !verifyType(outputType, array$1(NumberType))) {\n return context.error(`Type ${toString$1(outputType)} is not interpolatable.`);\n }\n return new Interpolate(outputType, operator, interpolation, input, stops);\n }\n evaluate(ctx) {\n const labels = this.labels;\n const outputs = this.outputs;\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n const value = this.input.evaluate(ctx);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\n const index = findStopLessThanOrEqualTo(labels, value);\n const lower = labels[index];\n const upper = labels[index + 1];\n const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper);\n const outputLower = outputs[index].evaluate(ctx);\n const outputUpper = outputs[index + 1].evaluate(ctx);\n switch (this.operator) {\n case 'interpolate':\n return interpolate[this.type.kind](outputLower, outputUpper, t);\n case 'interpolate-hcl':\n return interpolate.color(outputLower, outputUpper, t, 'hcl');\n case 'interpolate-lab':\n return interpolate.color(outputLower, outputUpper, t, 'lab');\n }\n }\n eachChild(fn) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n outputDefined() {\n return this.outputs.every(out => out.outputDefined());\n }\n}\n/**\n * Returns a ratio that can be used to interpolate between exponential function\n * stops.\n * How it works: Two consecutive stop values define a (scaled and shifted) exponential function `f(x) = a * base^x + b`, where `base` is the user-specified base,\n * and `a` and `b` are constants affording sufficient degrees of freedom to fit\n * the function to the given stops.\n *\n * Here's a bit of algebra that lets us compute `f(x)` directly from the stop\n * values without explicitly solving for `a` and `b`:\n *\n * First stop value: `f(x0) = y0 = a * base^x0 + b`\n * Second stop value: `f(x1) = y1 = a * base^x1 + b`\n * => `y1 - y0 = a(base^x1 - base^x0)`\n * => `a = (y1 - y0)/(base^x1 - base^x0)`\n *\n * Desired value: `f(x) = y = a * base^x + b`\n * => `f(x) = y0 + a * (base^x - base^x0)`\n *\n * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a\n * little algebra:\n * ```\n * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)\n * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)\n * ```\n *\n * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have\n * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as\n * an interpolation factor between the two stops' output values.\n *\n * (Note: a slightly different form for `ratio`,\n * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer\n * expensive `Math.pow()` operations.)\n *\n * @private\n*/\nfunction exponentialInterpolation(input, base, lowerValue, upperValue) {\n const difference = upperValue - lowerValue;\n const progress = input - lowerValue;\n if (difference === 0) {\n return 0;\n }\n else if (base === 1) {\n return progress / difference;\n }\n else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n\nclass Coalesce {\n constructor(type, args) {\n this.type = type;\n this.args = args;\n }\n static parse(args, context) {\n if (args.length < 2) {\n return context.error('Expectected at least one argument.');\n }\n let outputType = null;\n const expectedType = context.expectedType;\n if (expectedType && expectedType.kind !== 'value') {\n outputType = expectedType;\n }\n const parsedArgs = [];\n for (const arg of args.slice(1)) {\n const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, { typeAnnotation: 'omit' });\n if (!parsed)\n return null;\n outputType = outputType || parsed.type;\n parsedArgs.push(parsed);\n }\n if (!outputType)\n throw new Error('No output type');\n // Above, we parse arguments without inferred type annotation so that\n // they don't produce a runtime error for `null` input, which would\n // preempt the desired null-coalescing behavior.\n // Thus, if any of our arguments would have needed an annotation, we\n // need to wrap the enclosing coalesce expression with it instead.\n const needsAnnotation = expectedType &&\n parsedArgs.some(arg => checkSubtype(expectedType, arg.type));\n return needsAnnotation ?\n new Coalesce(ValueType, parsedArgs) :\n new Coalesce(outputType, parsedArgs);\n }\n evaluate(ctx) {\n let result = null;\n let argCount = 0;\n let requestedImageName;\n for (const arg of this.args) {\n argCount++;\n result = arg.evaluate(ctx);\n // we need to keep track of the first requested image in a coalesce statement\n // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire\n if (result && result instanceof ResolvedImage && !result.available) {\n if (!requestedImageName) {\n requestedImageName = result.name;\n }\n result = null;\n if (argCount === this.args.length) {\n result = requestedImageName;\n }\n }\n if (result !== null)\n break;\n }\n return result;\n }\n eachChild(fn) {\n this.args.forEach(fn);\n }\n outputDefined() {\n return this.args.every(arg => arg.outputDefined());\n }\n}\n\nfunction isComparableType(op, type) {\n if (op === '==' || op === '!=') {\n // equality operator\n return type.kind === 'boolean' ||\n type.kind === 'string' ||\n type.kind === 'number' ||\n type.kind === 'null' ||\n type.kind === 'value';\n }\n else {\n // ordering operator\n return type.kind === 'string' ||\n type.kind === 'number' ||\n type.kind === 'value';\n }\n}\nfunction eq(ctx, a, b) { return a === b; }\nfunction neq(ctx, a, b) { return a !== b; }\nfunction lt(ctx, a, b) { return a < b; }\nfunction gt(ctx, a, b) { return a > b; }\nfunction lteq(ctx, a, b) { return a <= b; }\nfunction gteq(ctx, a, b) { return a >= b; }\nfunction eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; }\nfunction neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); }\nfunction ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; }\nfunction gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; }\nfunction lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; }\nfunction gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; }\n/**\n * Special form for comparison operators, implementing the signatures:\n * - (T, T, ?Collator) => boolean\n * - (T, value, ?Collator) => boolean\n * - (value, T, ?Collator) => boolean\n *\n * For inequalities, T must be either value, string, or number. For ==/!=, it\n * can also be boolean or null.\n *\n * Equality semantics are equivalent to Javascript's strict equality (===/!==)\n * -- i.e., when the arguments' types don't match, == evaluates to false, != to\n * true.\n *\n * When types don't match in an ordering comparison, a runtime error is thrown.\n *\n * @private\n */\nfunction makeComparison(op, compareBasic, compareWithCollator) {\n const isOrderComparison = op !== '==' && op !== '!=';\n return class Comparison {\n constructor(lhs, rhs, collator) {\n this.type = BooleanType;\n this.lhs = lhs;\n this.rhs = rhs;\n this.collator = collator;\n this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value';\n }\n static parse(args, context) {\n if (args.length !== 3 && args.length !== 4)\n return context.error('Expected two or three arguments.');\n const op = args[0];\n let lhs = context.parse(args[1], 1, ValueType);\n if (!lhs)\n return null;\n if (!isComparableType(op, lhs.type)) {\n return context.concat(1).error(`\"${op}\" comparisons are not supported for type '${toString$1(lhs.type)}'.`);\n }\n let rhs = context.parse(args[2], 2, ValueType);\n if (!rhs)\n return null;\n if (!isComparableType(op, rhs.type)) {\n return context.concat(2).error(`\"${op}\" comparisons are not supported for type '${toString$1(rhs.type)}'.`);\n }\n if (lhs.type.kind !== rhs.type.kind &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value') {\n return context.error(`Cannot compare types '${toString$1(lhs.type)}' and '${toString$1(rhs.type)}'.`);\n }\n if (isOrderComparison) {\n // typing rules specific to less/greater than operators\n if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') {\n // (value, T)\n lhs = new Assertion(rhs.type, [lhs]);\n }\n else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') {\n // (T, value)\n rhs = new Assertion(lhs.type, [rhs]);\n }\n }\n let collator = null;\n if (args.length === 4) {\n if (lhs.type.kind !== 'string' &&\n rhs.type.kind !== 'string' &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value') {\n return context.error('Cannot use collator to compare non-string types.');\n }\n collator = context.parse(args[3], 3, CollatorType);\n if (!collator)\n return null;\n }\n return new Comparison(lhs, rhs, collator);\n }\n evaluate(ctx) {\n const lhs = this.lhs.evaluate(ctx);\n const rhs = this.rhs.evaluate(ctx);\n if (isOrderComparison && this.hasUntypedArgument) {\n const lt = typeOf(lhs);\n const rt = typeOf(rhs);\n // check that type is string or number, and equal\n if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) {\n throw new RuntimeError(`Expected arguments for \"${op}\" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`);\n }\n }\n if (this.collator && !isOrderComparison && this.hasUntypedArgument) {\n const lt = typeOf(lhs);\n const rt = typeOf(rhs);\n if (lt.kind !== 'string' || rt.kind !== 'string') {\n return compareBasic(ctx, lhs, rhs);\n }\n }\n return this.collator ?\n compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) :\n compareBasic(ctx, lhs, rhs);\n }\n eachChild(fn) {\n fn(this.lhs);\n fn(this.rhs);\n if (this.collator) {\n fn(this.collator);\n }\n }\n outputDefined() {\n return true;\n }\n };\n}\nconst Equals = makeComparison('==', eq, eqCollate);\nconst NotEquals = makeComparison('!=', neq, neqCollate);\nconst LessThan = makeComparison('<', lt, ltCollate);\nconst GreaterThan = makeComparison('>', gt, gtCollate);\nconst LessThanOrEqual = makeComparison('<=', lteq, lteqCollate);\nconst GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate);\n\nclass CollatorExpression {\n constructor(caseSensitive, diacriticSensitive, locale) {\n this.type = CollatorType;\n this.locale = locale;\n this.caseSensitive = caseSensitive;\n this.diacriticSensitive = diacriticSensitive;\n }\n static parse(args, context) {\n if (args.length !== 2)\n return context.error('Expected one argument.');\n const options = args[1];\n if (typeof options !== 'object' || Array.isArray(options))\n return context.error('Collator options argument must be an object.');\n const caseSensitive = context.parse(options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType);\n if (!caseSensitive)\n return null;\n const diacriticSensitive = context.parse(options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType);\n if (!diacriticSensitive)\n return null;\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale)\n return null;\n }\n return new CollatorExpression(caseSensitive, diacriticSensitive, locale);\n }\n evaluate(ctx) {\n return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null);\n }\n eachChild(fn) {\n fn(this.caseSensitive);\n fn(this.diacriticSensitive);\n if (this.locale) {\n fn(this.locale);\n }\n }\n outputDefined() {\n // Technically the set of possible outputs is the combinatoric set of Collators produced\n // by all possible outputs of locale/caseSensitive/diacriticSensitive\n // But for the primary use of Collators in comparison operators, we ignore the Collator's\n // possible outputs anyway, so we can get away with leaving this false for now.\n return false;\n }\n}\n\nclass NumberFormat {\n constructor(number, locale, currency, minFractionDigits, maxFractionDigits) {\n this.type = StringType;\n this.number = number;\n this.locale = locale;\n this.currency = currency;\n this.minFractionDigits = minFractionDigits;\n this.maxFractionDigits = maxFractionDigits;\n }\n static parse(args, context) {\n if (args.length !== 3)\n return context.error('Expected two arguments.');\n const number = context.parse(args[1], 1, NumberType);\n if (!number)\n return null;\n const options = args[2];\n if (typeof options !== 'object' || Array.isArray(options))\n return context.error('NumberFormat options argument must be an object.');\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale)\n return null;\n }\n let currency = null;\n if (options['currency']) {\n currency = context.parse(options['currency'], 1, StringType);\n if (!currency)\n return null;\n }\n let minFractionDigits = null;\n if (options['min-fraction-digits']) {\n minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType);\n if (!minFractionDigits)\n return null;\n }\n let maxFractionDigits = null;\n if (options['max-fraction-digits']) {\n maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType);\n if (!maxFractionDigits)\n return null;\n }\n return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits);\n }\n evaluate(ctx) {\n return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], {\n style: this.currency ? 'currency' : 'decimal',\n currency: this.currency ? this.currency.evaluate(ctx) : undefined,\n minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined,\n maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined,\n }).format(this.number.evaluate(ctx));\n }\n eachChild(fn) {\n fn(this.number);\n if (this.locale) {\n fn(this.locale);\n }\n if (this.currency) {\n fn(this.currency);\n }\n if (this.minFractionDigits) {\n fn(this.minFractionDigits);\n }\n if (this.maxFractionDigits) {\n fn(this.maxFractionDigits);\n }\n }\n outputDefined() {\n return false;\n }\n}\n\nclass FormatExpression {\n constructor(sections) {\n this.type = FormattedType;\n this.sections = sections;\n }\n static parse(args, context) {\n if (args.length < 2) {\n return context.error('Expected at least one argument.');\n }\n const firstArg = args[1];\n if (!Array.isArray(firstArg) && typeof firstArg === 'object') {\n return context.error('First argument must be an image or text section.');\n }\n const sections = [];\n let nextTokenMayBeObject = false;\n for (let i = 1; i <= args.length - 1; ++i) {\n const arg = args[i];\n if (nextTokenMayBeObject && typeof arg === 'object' && !Array.isArray(arg)) {\n nextTokenMayBeObject = false;\n let scale = null;\n if (arg['font-scale']) {\n scale = context.parse(arg['font-scale'], 1, NumberType);\n if (!scale)\n return null;\n }\n let font = null;\n if (arg['text-font']) {\n font = context.parse(arg['text-font'], 1, array$1(StringType));\n if (!font)\n return null;\n }\n let textColor = null;\n if (arg['text-color']) {\n textColor = context.parse(arg['text-color'], 1, ColorType);\n if (!textColor)\n return null;\n }\n const lastExpression = sections[sections.length - 1];\n lastExpression.scale = scale;\n lastExpression.font = font;\n lastExpression.textColor = textColor;\n }\n else {\n const content = context.parse(args[i], 1, ValueType);\n if (!content)\n return null;\n const kind = content.type.kind;\n if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage')\n return context.error('Formatted text type must be \\'string\\', \\'value\\', \\'image\\' or \\'null\\'.');\n nextTokenMayBeObject = true;\n sections.push({ content, scale: null, font: null, textColor: null });\n }\n }\n return new FormatExpression(sections);\n }\n evaluate(ctx) {\n const evaluateSection = section => {\n const evaluatedContent = section.content.evaluate(ctx);\n if (typeOf(evaluatedContent) === ResolvedImageType) {\n return new FormattedSection('', evaluatedContent, null, null, null);\n }\n return new FormattedSection(toString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null);\n };\n return new Formatted(this.sections.map(evaluateSection));\n }\n eachChild(fn) {\n for (const section of this.sections) {\n fn(section.content);\n if (section.scale) {\n fn(section.scale);\n }\n if (section.font) {\n fn(section.font);\n }\n if (section.textColor) {\n fn(section.textColor);\n }\n }\n }\n outputDefined() {\n // Technically the combinatoric set of all children\n // Usually, this.text will be undefined anyway\n return false;\n }\n}\n\nclass ImageExpression {\n constructor(input) {\n this.type = ResolvedImageType;\n this.input = input;\n }\n static parse(args, context) {\n if (args.length !== 2) {\n return context.error('Expected two arguments.');\n }\n const name = context.parse(args[1], 1, StringType);\n if (!name)\n return context.error('No image name provided.');\n return new ImageExpression(name);\n }\n evaluate(ctx) {\n const evaluatedImageName = this.input.evaluate(ctx);\n const value = ResolvedImage.fromString(evaluatedImageName);\n if (value && ctx.availableImages)\n value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1;\n return value;\n }\n eachChild(fn) {\n fn(this.input);\n }\n outputDefined() {\n // The output of image is determined by the list of available images in the evaluation context\n return false;\n }\n}\n\nclass Length {\n constructor(input) {\n this.type = NumberType;\n this.input = input;\n }\n static parse(args, context) {\n if (args.length !== 2)\n return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);\n const input = context.parse(args[1], 1);\n if (!input)\n return null;\n if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value')\n return context.error(`Expected argument of type string or array, but found ${toString$1(input.type)} instead.`);\n return new Length(input);\n }\n evaluate(ctx) {\n const input = this.input.evaluate(ctx);\n if (typeof input === 'string') {\n // The length may be affected by surrogate pairs.\n return [...input].length;\n }\n else if (Array.isArray(input)) {\n return input.length;\n }\n else {\n throw new RuntimeError(`Expected value to be of type string or array, but found ${toString$1(typeOf(input))} instead.`);\n }\n }\n eachChild(fn) {\n fn(this.input);\n }\n outputDefined() {\n return false;\n }\n}\n\nconst EXTENT = 8192;\nfunction getTileCoordinates(p, canonical) {\n const x = mercatorXfromLng(p[0]);\n const y = mercatorYfromLat(p[1]);\n const tilesAtZoom = Math.pow(2, canonical.z);\n return [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)];\n}\nfunction getLngLatFromTileCoord(coord, canonical) {\n const tilesAtZoom = Math.pow(2, canonical.z);\n const x = (coord[0] / EXTENT + canonical.x) / tilesAtZoom;\n const y = (coord[1] / EXTENT + canonical.y) / tilesAtZoom;\n return [lngFromMercatorXfromLng(x), latFromMercatorY(y)];\n}\nfunction mercatorXfromLng(lng) {\n return (180 + lng) / 360;\n}\nfunction lngFromMercatorXfromLng(mercatorX) {\n return mercatorX * 360 - 180;\n}\nfunction mercatorYfromLat(lat) {\n return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;\n}\nfunction latFromMercatorY(mercatorY) {\n return 360 / Math.PI * Math.atan(Math.exp((180 - mercatorY * 360) * Math.PI / 180)) - 90;\n}\nfunction updateBBox(bbox, coord) {\n bbox[0] = Math.min(bbox[0], coord[0]);\n bbox[1] = Math.min(bbox[1], coord[1]);\n bbox[2] = Math.max(bbox[2], coord[0]);\n bbox[3] = Math.max(bbox[3], coord[1]);\n}\nfunction boxWithinBox(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 rayIntersect(p, p1, p2) {\n return ((p1[1] > p[1]) !== (p2[1] > p[1])) && (p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]);\n}\nfunction pointOnBoundary(p, p1, p2) {\n const x1 = p[0] - p1[0];\n const y1 = p[1] - p1[1];\n const x2 = p[0] - p2[0];\n const y2 = p[1] - p2[1];\n return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0);\n}\n// a, b are end points for line segment1, c and d are end points for line segment2\nfunction segmentIntersectSegment(a, b, c, d) {\n // check if two segments are parallel or not\n // precondition is end point a, b is inside polygon, if line a->b is\n // parallel to polygon edge c->d, then a->b won't intersect with c->d\n const vectorP = [b[0] - a[0], b[1] - a[1]];\n const vectorQ = [d[0] - c[0], d[1] - c[1]];\n if (perp(vectorQ, vectorP) === 0)\n return false;\n // If lines are intersecting with each other, the relative location should be:\n // a and b lie in different sides of segment c->d\n // c and d lie in different sides of segment a->b\n if (twoSided(a, b, c, d) && twoSided(c, d, a, b))\n return true;\n return false;\n}\nfunction lineIntersectPolygon(p1, p2, polygon) {\n for (const ring of polygon) {\n // loop through every edge of the ring\n for (let j = 0; j < ring.length - 1; ++j) {\n if (segmentIntersectSegment(p1, p2, ring[j], ring[j + 1])) {\n return true;\n }\n }\n }\n return false;\n}\n// ray casting algorithm for detecting if point is in polygon\nfunction pointWithinPolygon(point, rings, trueIfOnBoundary = false) {\n let inside = false;\n for (const ring of rings) {\n for (let j = 0; j < ring.length - 1; j++) {\n if (pointOnBoundary(point, ring[j], ring[j + 1]))\n return trueIfOnBoundary;\n if (rayIntersect(point, ring[j], ring[j + 1]))\n inside = !inside;\n }\n }\n return inside;\n}\nfunction pointWithinPolygons(point, polygons) {\n for (const polygon of polygons) {\n if (pointWithinPolygon(point, polygon))\n return true;\n }\n return false;\n}\nfunction lineStringWithinPolygon(line, polygon) {\n // First, check if geometry points of line segments are all inside polygon\n for (const point of line) {\n if (!pointWithinPolygon(point, polygon)) {\n return false;\n }\n }\n // Second, check if there is line segment intersecting polygon edge\n for (let i = 0; i < line.length - 1; ++i) {\n if (lineIntersectPolygon(line[i], line[i + 1], polygon)) {\n return false;\n }\n }\n return true;\n}\nfunction lineStringWithinPolygons(line, polygons) {\n for (const polygon of polygons) {\n if (lineStringWithinPolygon(line, polygon))\n return true;\n }\n return false;\n}\nfunction perp(v1, v2) {\n return (v1[0] * v2[1] - v1[1] * v2[0]);\n}\n// check if p1 and p2 are in different sides of line segment q1->q2\nfunction twoSided(p1, p2, q1, q2) {\n // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3)\n const x1 = p1[0] - q1[0];\n const y1 = p1[1] - q1[1];\n const x2 = p2[0] - q1[0];\n const y2 = p2[1] - q1[1];\n const x3 = q2[0] - q1[0];\n const y3 = q2[1] - q1[1];\n const det1 = (x1 * y3 - x3 * y1);\n const det2 = (x2 * y3 - x3 * y2);\n if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0))\n return true;\n return false;\n}\n\nfunction getTilePolygon(coordinates, bbox, canonical) {\n const polygon = [];\n for (let i = 0; i < coordinates.length; i++) {\n const ring = [];\n for (let j = 0; j < coordinates[i].length; j++) {\n const coord = getTileCoordinates(coordinates[i][j], canonical);\n updateBBox(bbox, coord);\n ring.push(coord);\n }\n polygon.push(ring);\n }\n return polygon;\n}\nfunction getTilePolygons(coordinates, bbox, canonical) {\n const polygons = [];\n for (let i = 0; i < coordinates.length; i++) {\n const polygon = getTilePolygon(coordinates[i], bbox, canonical);\n polygons.push(polygon);\n }\n return polygons;\n}\nfunction updatePoint(p, bbox, polyBBox, worldSize) {\n if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) {\n const halfWorldSize = worldSize * 0.5;\n let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0;\n if (shift === 0) {\n shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0;\n }\n p[0] += shift;\n }\n updateBBox(bbox, p);\n}\nfunction resetBBox(bbox) {\n bbox[0] = bbox[1] = Infinity;\n bbox[2] = bbox[3] = -Infinity;\n}\nfunction getTilePoints(geometry, pointBBox, polyBBox, canonical) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const tilePoints = [];\n for (const points of geometry) {\n for (const point of points) {\n const p = [point.x + shifts[0], point.y + shifts[1]];\n updatePoint(p, pointBBox, polyBBox, worldSize);\n tilePoints.push(p);\n }\n }\n return tilePoints;\n}\nfunction getTileLines(geometry, lineBBox, polyBBox, canonical) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const tileLines = [];\n for (const line of geometry) {\n const tileLine = [];\n for (const point of line) {\n const p = [point.x + shifts[0], point.y + shifts[1]];\n updateBBox(lineBBox, p);\n tileLine.push(p);\n }\n tileLines.push(tileLine);\n }\n if (lineBBox[2] - lineBBox[0] <= worldSize / 2) {\n resetBBox(lineBBox);\n for (const line of tileLines) {\n for (const p of line) {\n updatePoint(p, lineBBox, polyBBox, worldSize);\n }\n }\n }\n return tileLines;\n}\nfunction pointsWithinPolygons(ctx, polygonGeometry) {\n const pointBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const canonical = ctx.canonicalID();\n if (polygonGeometry.type === 'Polygon') {\n const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n if (!boxWithinBox(pointBBox, polyBBox))\n return false;\n for (const point of tilePoints) {\n if (!pointWithinPolygon(point, tilePolygon))\n return false;\n }\n }\n if (polygonGeometry.type === 'MultiPolygon') {\n const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n if (!boxWithinBox(pointBBox, polyBBox))\n return false;\n for (const point of tilePoints) {\n if (!pointWithinPolygons(point, tilePolygons))\n return false;\n }\n }\n return true;\n}\nfunction linesWithinPolygons(ctx, polygonGeometry) {\n const lineBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const canonical = ctx.canonicalID();\n if (polygonGeometry.type === 'Polygon') {\n const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n if (!boxWithinBox(lineBBox, polyBBox))\n return false;\n for (const line of tileLines) {\n if (!lineStringWithinPolygon(line, tilePolygon))\n return false;\n }\n }\n if (polygonGeometry.type === 'MultiPolygon') {\n const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n if (!boxWithinBox(lineBBox, polyBBox))\n return false;\n for (const line of tileLines) {\n if (!lineStringWithinPolygons(line, tilePolygons))\n return false;\n }\n }\n return true;\n}\nclass Within {\n constructor(geojson, geometries) {\n this.type = BooleanType;\n this.geojson = geojson;\n this.geometries = geometries;\n }\n static parse(args, context) {\n if (args.length !== 2)\n return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n if (isValue(args[1])) {\n const geojson = args[1];\n if (geojson.type === 'FeatureCollection') {\n const polygonsCoords = [];\n for (const polygon of geojson.features) {\n const { type, coordinates } = polygon.geometry;\n if (type === 'Polygon') {\n polygonsCoords.push(coordinates);\n }\n if (type === 'MultiPolygon') {\n polygonsCoords.push(...coordinates);\n }\n }\n if (polygonsCoords.length) {\n const multipolygonWrapper = {\n type: 'MultiPolygon',\n coordinates: polygonsCoords\n };\n return new Within(geojson, multipolygonWrapper);\n }\n }\n else if (geojson.type === 'Feature') {\n const type = geojson.geometry.type;\n if (type === 'Polygon' || type === 'MultiPolygon') {\n return new Within(geojson, geojson.geometry);\n }\n }\n else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') {\n return new Within(geojson, geojson);\n }\n }\n return context.error('\\'within\\' expression requires valid geojson object that contains polygon geometry type.');\n }\n evaluate(ctx) {\n if (ctx.geometry() != null && ctx.canonicalID() != null) {\n if (ctx.geometryType() === 'Point') {\n return pointsWithinPolygons(ctx, this.geometries);\n }\n else if (ctx.geometryType() === 'LineString') {\n return linesWithinPolygons(ctx, this.geometries);\n }\n }\n return false;\n }\n eachChild() { }\n outputDefined() {\n return true;\n }\n}\n\nclass TinyQueue {\n constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) {\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._up(this.length++);\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\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 bestChild = (pos << 1) + 1; // initially it is the left child\n const right = bestChild + 1;\n\n if (right < this.length && compare(data[right], data[bestChild]) < 0) {\n bestChild = right;\n }\n if (compare(data[bestChild], item) >= 0) break;\n\n data[pos] = data[bestChild];\n pos = bestChild;\n }\n\n data[pos] = item;\n }\n}\n\nfunction quickselect(arr, k, left, right, compare) {\n quickselectStep(arr, k, left, 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\n/**\n * Classifies an array of rings into polygons with outer rings and holes\n * @param rings - the rings to classify\n * @param maxRings - the maximum number of rings to include in a polygon, use 0 to include all rings\n * @returns an array of polygons with internal rings as holes\n */\nfunction classifyRings(rings, maxRings) {\n const len = rings.length;\n if (len <= 1)\n return [rings];\n const polygons = [];\n let polygon;\n let ccw;\n for (const ring of rings) {\n const area = calculateSignedArea(ring);\n if (area === 0)\n continue;\n ring.area = Math.abs(area);\n if (ccw === undefined)\n ccw = area < 0;\n if (ccw === area < 0) {\n if (polygon)\n polygons.push(polygon);\n polygon = [ring];\n }\n else {\n polygon.push(ring);\n }\n }\n if (polygon)\n polygons.push(polygon);\n // Earcut performance degrades with the # of rings in a polygon. For this\n // reason, we limit strip out all but the `maxRings` largest rings.\n if (maxRings > 1) {\n for (let j = 0; j < polygons.length; j++) {\n if (polygons[j].length <= maxRings)\n continue;\n quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas);\n polygons[j] = polygons[j].slice(0, maxRings);\n }\n }\n return polygons;\n}\nfunction compareAreas(a, b) {\n return b.area - a.area;\n}\n/**\n * Returns the signed area for the polygon ring. Positive areas are exterior rings and\n * have a clockwise winding. Negative areas are interior rings and have a counter clockwise\n * ordering.\n *\n * @param ring - Exterior or interior ring\n * @returns Signed area\n */\nfunction calculateSignedArea(ring) {\n let sum = 0;\n for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {\n p1 = ring[i];\n p2 = ring[j];\n sum += (p2.x - p1.x) * (p1.y + p2.y);\n }\n return sum;\n}\n\n// This is taken from https://github.com/mapbox/cheap-ruler/ in order to take only the relevant parts\n// Values that define WGS84 ellipsoid model of the Earth\nconst RE = 6378.137; // equatorial radius\nconst FE = 1 / 298.257223563; // flattening\nconst E2 = FE * (2 - FE);\nconst RAD = Math.PI / 180;\nclass CheapRuler {\n constructor(lat) {\n // Curvature formulas from https://en.wikipedia.org/wiki/Earth_radius#Meridional\n const m = RAD * RE * 1000;\n const coslat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - coslat * coslat));\n const w = Math.sqrt(w2);\n // multipliers for converting longitude and latitude degrees into distance\n this.kx = m * w * coslat; // based on normal radius of curvature\n this.ky = m * w * w2 * (1 - E2); // based on meridonal radius of curvature\n }\n /**\n * Given two points of the form [longitude, latitude], returns the distance.\n *\n * @param a - point [longitude, latitude]\n * @param b - point [longitude, latitude]\n * @returns distance\n * @example\n * const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]);\n * //=distance\n */\n distance(a, b) {\n const dx = this.wrap(a[0] - b[0]) * this.kx;\n const dy = (a[1] - b[1]) * this.ky;\n return Math.sqrt(dx * dx + dy * dy);\n }\n /**\n * Returns an object of the form {point, index, t}, where point is closest point on the line\n * from the given point, index is the start index of the segment with the closest point,\n * and t is a parameter from 0 to 1 that indicates where the closest point is on that segment.\n *\n * @param line - an array of points that form the line\n * @param p - point [longitude, latitude]\n * @returns the nearest point, its index in the array and the proportion along the line\n * @example\n * const point = ruler.pointOnLine(line, [-67.04, 50.5]).point;\n * //=point\n */\n pointOnLine(line, p) {\n let minDist = Infinity;\n let minX, minY, minI, minT;\n for (let i = 0; i < line.length - 1; i++) {\n let x = line[i][0];\n let y = line[i][1];\n let dx = this.wrap(line[i + 1][0] - x) * this.kx;\n let dy = (line[i + 1][1] - y) * this.ky;\n let t = 0;\n if (dx !== 0 || dy !== 0) {\n t = (this.wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy);\n if (t > 1) {\n x = line[i + 1][0];\n y = line[i + 1][1];\n }\n else if (t > 0) {\n x += (dx / this.kx) * t;\n y += (dy / this.ky) * t;\n }\n }\n dx = this.wrap(p[0] - x) * this.kx;\n dy = (p[1] - y) * this.ky;\n const sqDist = dx * dx + dy * dy;\n if (sqDist < minDist) {\n minDist = sqDist;\n minX = x;\n minY = y;\n minI = i;\n minT = t;\n }\n }\n return {\n point: [minX, minY],\n index: minI,\n t: Math.max(0, Math.min(1, minT))\n };\n }\n wrap(deg) {\n while (deg < -180)\n deg += 360;\n while (deg > 180)\n deg -= 360;\n return deg;\n }\n}\n\nconst MinPointsSize = 100;\nconst MinLinePointsSize = 50;\nfunction compareDistPair(a, b) {\n return b[0] - a[0];\n}\nfunction getRangeSize(range) {\n return range[1] - range[0] + 1;\n}\nfunction isRangeSafe(range, threshold) {\n return range[1] >= range[0] && range[1] < threshold;\n}\nfunction splitRange(range, isLine) {\n if (range[0] > range[1]) {\n return [null, null];\n }\n const size = getRangeSize(range);\n if (isLine) {\n if (size === 2) {\n return [range, null];\n }\n const size1 = Math.floor(size / 2);\n return [[range[0], range[0] + size1],\n [range[0] + size1, range[1]]];\n }\n if (size === 1) {\n return [range, null];\n }\n const size1 = Math.floor(size / 2) - 1;\n return [[range[0], range[0] + size1],\n [range[0] + size1 + 1, range[1]]];\n}\nfunction getBBox(coords, range) {\n if (!isRangeSafe(range, coords.length)) {\n return [Infinity, Infinity, -Infinity, -Infinity];\n }\n const bbox = [Infinity, Infinity, -Infinity, -Infinity];\n for (let i = range[0]; i <= range[1]; ++i) {\n updateBBox(bbox, coords[i]);\n }\n return bbox;\n}\nfunction getPolygonBBox(polygon) {\n const bbox = [Infinity, Infinity, -Infinity, -Infinity];\n for (const ring of polygon) {\n for (const coord of ring) {\n updateBBox(bbox, coord);\n }\n }\n return bbox;\n}\nfunction isValidBBox(bbox) {\n return bbox[0] !== -Infinity && bbox[1] !== -Infinity && bbox[2] !== Infinity && bbox[3] !== Infinity;\n}\n// Calculate the distance between two bounding boxes.\n// Calculate the delta in x and y direction, and use two fake points {0.0, 0.0}\n// and {dx, dy} to calculate the distance. Distance will be 0.0 if bounding box are overlapping.\nfunction bboxToBBoxDistance(bbox1, bbox2, ruler) {\n if (!isValidBBox(bbox1) || !isValidBBox(bbox2)) {\n return NaN;\n }\n let dx = 0.0;\n let dy = 0.0;\n // bbox1 in left side\n if (bbox1[2] < bbox2[0]) {\n dx = bbox2[0] - bbox1[2];\n }\n // bbox1 in right side\n if (bbox1[0] > bbox2[2]) {\n dx = bbox1[0] - bbox2[2];\n }\n // bbox1 in above side\n if (bbox1[1] > bbox2[3]) {\n dy = bbox1[1] - bbox2[3];\n }\n // bbox1 in down side\n if (bbox1[3] < bbox2[1]) {\n dy = bbox2[1] - bbox1[3];\n }\n return ruler.distance([0.0, 0.0], [dx, dy]);\n}\nfunction pointToLineDistance(point, line, ruler) {\n const nearestPoint = ruler.pointOnLine(line, point);\n return ruler.distance(point, nearestPoint.point);\n}\nfunction segmentToSegmentDistance(p1, p2, q1, q2, ruler) {\n const dist1 = Math.min(pointToLineDistance(p1, [q1, q2], ruler), pointToLineDistance(p2, [q1, q2], ruler));\n const dist2 = Math.min(pointToLineDistance(q1, [p1, p2], ruler), pointToLineDistance(q2, [p1, p2], ruler));\n return Math.min(dist1, dist2);\n}\nfunction lineToLineDistance(line1, range1, line2, range2, ruler) {\n const rangeSafe = isRangeSafe(range1, line1.length) && isRangeSafe(range2, line2.length);\n if (!rangeSafe) {\n return Infinity;\n }\n let dist = Infinity;\n for (let i = range1[0]; i < range1[1]; ++i) {\n const p1 = line1[i];\n const p2 = line1[i + 1];\n for (let j = range2[0]; j < range2[1]; ++j) {\n const q1 = line2[j];\n const q2 = line2[j + 1];\n if (segmentIntersectSegment(p1, p2, q1, q2)) {\n return 0.0;\n }\n dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler));\n }\n }\n return dist;\n}\nfunction pointsToPointsDistance(points1, range1, points2, range2, ruler) {\n const rangeSafe = isRangeSafe(range1, points1.length) && isRangeSafe(range2, points2.length);\n if (!rangeSafe) {\n return NaN;\n }\n let dist = Infinity;\n for (let i = range1[0]; i <= range1[1]; ++i) {\n for (let j = range2[0]; j <= range2[1]; ++j) {\n dist = Math.min(dist, ruler.distance(points1[i], points2[j]));\n if (dist === 0.0) {\n return dist;\n }\n }\n }\n return dist;\n}\nfunction pointToPolygonDistance(point, polygon, ruler) {\n if (pointWithinPolygon(point, polygon, true)) {\n return 0.0;\n }\n let dist = Infinity;\n for (const ring of polygon) {\n const front = ring[0];\n const back = ring[ring.length - 1];\n if (front !== back) {\n dist = Math.min(dist, pointToLineDistance(point, [back, front], ruler));\n if (dist === 0.0) {\n return dist;\n }\n }\n const nearestPoint = ruler.pointOnLine(ring, point);\n dist = Math.min(dist, ruler.distance(point, nearestPoint.point));\n if (dist === 0.0) {\n return dist;\n }\n }\n return dist;\n}\nfunction lineToPolygonDistance(line, range, polygon, ruler) {\n if (!isRangeSafe(range, line.length)) {\n return NaN;\n }\n for (let i = range[0]; i <= range[1]; ++i) {\n if (pointWithinPolygon(line[i], polygon, true)) {\n return 0.0;\n }\n }\n let dist = Infinity;\n for (let i = range[0]; i < range[1]; ++i) {\n const p1 = line[i];\n const p2 = line[i + 1];\n for (const ring of polygon) {\n for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) {\n const q1 = ring[k];\n const q2 = ring[j];\n if (segmentIntersectSegment(p1, p2, q1, q2)) {\n return 0.0;\n }\n dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler));\n }\n }\n }\n return dist;\n}\nfunction polygonIntersect(poly1, poly2) {\n for (const ring of poly1) {\n for (const point of ring) {\n if (pointWithinPolygon(point, poly2, true)) {\n return true;\n }\n }\n }\n return false;\n}\nfunction polygonToPolygonDistance(polygon1, polygon2, ruler, currentMiniDist = Infinity) {\n const bbox1 = getPolygonBBox(polygon1);\n const bbox2 = getPolygonBBox(polygon2);\n if (currentMiniDist !== Infinity && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) {\n return currentMiniDist;\n }\n if (boxWithinBox(bbox1, bbox2)) {\n if (polygonIntersect(polygon1, polygon2)) {\n return 0.0;\n }\n }\n else if (polygonIntersect(polygon2, polygon1)) {\n return 0.0;\n }\n let dist = Infinity;\n for (const ring1 of polygon1) {\n for (let i = 0, len1 = ring1.length, l = len1 - 1; i < len1; l = i++) {\n const p1 = ring1[l];\n const p2 = ring1[i];\n for (const ring2 of polygon2) {\n for (let j = 0, len2 = ring2.length, k = len2 - 1; j < len2; k = j++) {\n const q1 = ring2[k];\n const q2 = ring2[j];\n if (segmentIntersectSegment(p1, p2, q1, q2)) {\n return 0.0;\n }\n dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler));\n }\n }\n }\n }\n return dist;\n}\nfunction updateQueue(distQueue, miniDist, ruler, points, polyBBox, rangeA) {\n if (!rangeA) {\n return;\n }\n const tempDist = bboxToBBoxDistance(getBBox(points, rangeA), polyBBox, ruler);\n // Insert new pair to the queue if the bbox distance is less than\n // miniDist, The pair with biggest distance will be at the top\n if (tempDist < miniDist) {\n distQueue.push([tempDist, rangeA, [0, 0]]);\n }\n}\nfunction updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, range1, range2) {\n if (!range1 || !range2) {\n return;\n }\n const tempDist = bboxToBBoxDistance(getBBox(pointSet1, range1), getBBox(pointSet2, range2), ruler);\n // Insert new pair to the queue if the bbox distance is less than\n // miniDist, The pair with biggest distance will be at the top\n if (tempDist < miniDist) {\n distQueue.push([tempDist, range1, range2]);\n }\n}\n// Divide and conquer, the time complexity is O(n*lgn), faster than Brute force\n// O(n*n) Most of the time, use index for in-place processing.\nfunction pointsToPolygonDistance(points, isLine, polygon, ruler, currentMiniDist = Infinity) {\n let miniDist = Math.min(ruler.distance(points[0], polygon[0][0]), currentMiniDist);\n if (miniDist === 0.0) {\n return miniDist;\n }\n const distQueue = new TinyQueue([[0, [0, points.length - 1], [0, 0]]], compareDistPair);\n const polyBBox = getPolygonBBox(polygon);\n while (distQueue.length > 0) {\n const distPair = distQueue.pop();\n if (distPair[0] >= miniDist) {\n continue;\n }\n const range = distPair[1];\n // In case the set size are relatively small, we could use brute-force directly\n const threshold = isLine ? MinLinePointsSize : MinPointsSize;\n if (getRangeSize(range) <= threshold) {\n if (!isRangeSafe(range, points.length)) {\n return NaN;\n }\n if (isLine) {\n const tempDist = lineToPolygonDistance(points, range, polygon, ruler);\n if (isNaN(tempDist) || tempDist === 0.0) {\n return tempDist;\n }\n miniDist = Math.min(miniDist, tempDist);\n }\n else {\n for (let i = range[0]; i <= range[1]; ++i) {\n const tempDist = pointToPolygonDistance(points[i], polygon, ruler);\n miniDist = Math.min(miniDist, tempDist);\n if (miniDist === 0.0) {\n return 0.0;\n }\n }\n }\n }\n else {\n const newRangesA = splitRange(range, isLine);\n updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[0]);\n updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[1]);\n }\n }\n return miniDist;\n}\nfunction pointSetToPointSetDistance(pointSet1, isLine1, pointSet2, isLine2, ruler, currentMiniDist = Infinity) {\n let miniDist = Math.min(currentMiniDist, ruler.distance(pointSet1[0], pointSet2[0]));\n if (miniDist === 0.0) {\n return miniDist;\n }\n const distQueue = new TinyQueue([[0, [0, pointSet1.length - 1], [0, pointSet2.length - 1]]], compareDistPair);\n while (distQueue.length > 0) {\n const distPair = distQueue.pop();\n if (distPair[0] >= miniDist) {\n continue;\n }\n const rangeA = distPair[1];\n const rangeB = distPair[2];\n const threshold1 = isLine1 ? MinLinePointsSize : MinPointsSize;\n const threshold2 = isLine2 ? MinLinePointsSize : MinPointsSize;\n // In case the set size are relatively small, we could use brute-force directly\n if (getRangeSize(rangeA) <= threshold1 && getRangeSize(rangeB) <= threshold2) {\n if (!isRangeSafe(rangeA, pointSet1.length) && isRangeSafe(rangeB, pointSet2.length)) {\n return NaN;\n }\n let tempDist;\n if (isLine1 && isLine2) {\n tempDist = lineToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler);\n miniDist = Math.min(miniDist, tempDist);\n }\n else if (isLine1 && !isLine2) {\n const sublibe = pointSet1.slice(rangeA[0], rangeA[1] + 1);\n for (let i = rangeB[0]; i <= rangeB[1]; ++i) {\n tempDist = pointToLineDistance(pointSet2[i], sublibe, ruler);\n miniDist = Math.min(miniDist, tempDist);\n if (miniDist === 0.0) {\n return miniDist;\n }\n }\n }\n else if (!isLine1 && isLine2) {\n const sublibe = pointSet2.slice(rangeB[0], rangeB[1] + 1);\n for (let i = rangeA[0]; i <= rangeA[1]; ++i) {\n tempDist = pointToLineDistance(pointSet1[i], sublibe, ruler);\n miniDist = Math.min(miniDist, tempDist);\n if (miniDist === 0.0) {\n return miniDist;\n }\n }\n }\n else {\n tempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler);\n miniDist = Math.min(miniDist, tempDist);\n }\n }\n else {\n const newRangesA = splitRange(rangeA, isLine1);\n const newRangesB = splitRange(rangeB, isLine2);\n updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[0]);\n updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[1]);\n updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[0]);\n updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[1]);\n }\n }\n return miniDist;\n}\nfunction pointToGeometryDistance(ctx, geometries) {\n const tilePoints = ctx.geometry();\n const pointPosition = tilePoints.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical));\n if (tilePoints.length === 0) {\n return NaN;\n }\n const ruler = new CheapRuler(pointPosition[0][1]);\n let dist = Infinity;\n for (const geometry of geometries) {\n switch (geometry.type) {\n case 'Point':\n dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, [geometry.coordinates], false, ruler, dist));\n break;\n case 'LineString':\n dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, geometry.coordinates, true, ruler, dist));\n break;\n case 'Polygon':\n dist = Math.min(dist, pointsToPolygonDistance(pointPosition, false, geometry.coordinates, ruler, dist));\n break;\n }\n if (dist === 0.0) {\n return dist;\n }\n }\n return dist;\n}\nfunction lineStringToGeometryDistance(ctx, geometries) {\n const tileLine = ctx.geometry();\n const linePositions = tileLine.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical));\n if (tileLine.length === 0) {\n return NaN;\n }\n const ruler = new CheapRuler(linePositions[0][1]);\n let dist = Infinity;\n for (const geometry of geometries) {\n switch (geometry.type) {\n case 'Point':\n dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, [geometry.coordinates], false, ruler, dist));\n break;\n case 'LineString':\n dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, geometry.coordinates, true, ruler, dist));\n break;\n case 'Polygon':\n dist = Math.min(dist, pointsToPolygonDistance(linePositions, true, geometry.coordinates, ruler, dist));\n break;\n }\n if (dist === 0.0) {\n return dist;\n }\n }\n return dist;\n}\nfunction polygonToGeometryDistance(ctx, geometries) {\n const tilePolygon = ctx.geometry();\n if (tilePolygon.length === 0 || tilePolygon[0].length === 0) {\n return NaN;\n }\n const polygons = classifyRings(tilePolygon, 0).map(polygon => {\n return polygon.map(ring => {\n return ring.map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical));\n });\n });\n const ruler = new CheapRuler(polygons[0][0][0][1]);\n let dist = Infinity;\n for (const geometry of geometries) {\n for (const polygon of polygons) {\n switch (geometry.type) {\n case 'Point':\n dist = Math.min(dist, pointsToPolygonDistance([geometry.coordinates], false, polygon, ruler, dist));\n break;\n case 'LineString':\n dist = Math.min(dist, pointsToPolygonDistance(geometry.coordinates, true, polygon, ruler, dist));\n break;\n case 'Polygon':\n dist = Math.min(dist, polygonToPolygonDistance(polygon, geometry.coordinates, ruler, dist));\n break;\n }\n if (dist === 0.0) {\n return dist;\n }\n }\n }\n return dist;\n}\nfunction toSimpleGeometry(geometry) {\n if (geometry.type === 'MultiPolygon') {\n return geometry.coordinates.map(polygon => {\n return {\n type: 'Polygon',\n coordinates: polygon\n };\n });\n }\n if (geometry.type === 'MultiLineString') {\n return geometry.coordinates.map(lineString => {\n return {\n type: 'LineString',\n coordinates: lineString\n };\n });\n }\n if (geometry.type === 'MultiPoint') {\n return geometry.coordinates.map(point => {\n return {\n type: 'Point',\n coordinates: point\n };\n });\n }\n return [geometry];\n}\nclass Distance {\n constructor(geojson, geometries) {\n this.type = NumberType;\n this.geojson = geojson;\n this.geometries = geometries;\n }\n static parse(args, context) {\n if (args.length !== 2)\n return context.error(`'distance' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n if (isValue(args[1])) {\n const geojson = args[1];\n if (geojson.type === 'FeatureCollection') {\n return new Distance(geojson, geojson.features.map(feature => toSimpleGeometry(feature.geometry)).flat());\n }\n else if (geojson.type === 'Feature') {\n return new Distance(geojson, toSimpleGeometry(geojson.geometry));\n }\n else if ('type' in geojson && 'coordinates' in geojson) {\n return new Distance(geojson, toSimpleGeometry(geojson));\n }\n }\n return context.error('\\'distance\\' expression requires valid geojson object that contains polygon geometry type.');\n }\n evaluate(ctx) {\n if (ctx.geometry() != null && ctx.canonicalID() != null) {\n if (ctx.geometryType() === 'Point') {\n return pointToGeometryDistance(ctx, this.geometries);\n }\n else if (ctx.geometryType() === 'LineString') {\n return lineStringToGeometryDistance(ctx, this.geometries);\n }\n else if (ctx.geometryType() === 'Polygon') {\n return polygonToGeometryDistance(ctx, this.geometries);\n }\n }\n return NaN;\n }\n eachChild() { }\n outputDefined() {\n return true;\n }\n}\n\nconst expressions$1 = {\n // special forms\n '==': Equals,\n '!=': NotEquals,\n '>': GreaterThan,\n '<': LessThan,\n '>=': GreaterThanOrEqual,\n '<=': LessThanOrEqual,\n 'array': Assertion,\n 'at': At,\n 'boolean': Assertion,\n 'case': Case,\n 'coalesce': Coalesce,\n 'collator': CollatorExpression,\n 'format': FormatExpression,\n 'image': ImageExpression,\n 'in': In,\n 'index-of': IndexOf,\n 'interpolate': Interpolate,\n 'interpolate-hcl': Interpolate,\n 'interpolate-lab': Interpolate,\n 'length': Length,\n 'let': Let,\n 'literal': Literal,\n 'match': Match,\n 'number': Assertion,\n 'number-format': NumberFormat,\n 'object': Assertion,\n 'slice': Slice,\n 'step': Step,\n 'string': Assertion,\n 'to-boolean': Coercion,\n 'to-color': Coercion,\n 'to-number': Coercion,\n 'to-string': Coercion,\n 'var': Var,\n 'within': Within,\n 'distance': Distance\n};\n\nclass CompoundExpression {\n constructor(name, type, evaluate, args) {\n this.name = name;\n this.type = type;\n this._evaluate = evaluate;\n this.args = args;\n }\n evaluate(ctx) {\n return this._evaluate(ctx, this.args);\n }\n eachChild(fn) {\n this.args.forEach(fn);\n }\n outputDefined() {\n return false;\n }\n static parse(args, context) {\n const op = args[0];\n const definition = CompoundExpression.definitions[op];\n if (!definition) {\n return context.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n }\n // Now check argument types against each signature\n const type = Array.isArray(definition) ?\n definition[0] : definition.type;\n const availableOverloads = Array.isArray(definition) ?\n [[definition[1], definition[2]]] :\n definition.overloads;\n const overloads = availableOverloads.filter(([signature]) => (!Array.isArray(signature) || // varags\n signature.length === args.length - 1 // correct param count\n ));\n let signatureContext = null;\n for (const [params, evaluate] of overloads) {\n // Use a fresh context for each attempted signature so that, if\n // we eventually succeed, we haven't polluted `context.errors`.\n signatureContext = new ParsingContext(context.registry, isExpressionConstant, context.path, null, context.scope);\n // First parse all the args, potentially coercing to the\n // types expected by this overload.\n const parsedArgs = [];\n let argParseFailed = false;\n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n const expectedType = Array.isArray(params) ?\n params[i - 1] :\n params.type;\n const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);\n if (!parsed) {\n argParseFailed = true;\n break;\n }\n parsedArgs.push(parsed);\n }\n if (argParseFailed) {\n // Couldn't coerce args of this overload to expected type, move\n // on to next one.\n continue;\n }\n if (Array.isArray(params)) {\n if (params.length !== parsedArgs.length) {\n signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`);\n continue;\n }\n }\n for (let i = 0; i < parsedArgs.length; i++) {\n const expected = Array.isArray(params) ? params[i] : params.type;\n const arg = parsedArgs[i];\n signatureContext.concat(i + 1).checkSubtype(expected, arg.type);\n }\n if (signatureContext.errors.length === 0) {\n return new CompoundExpression(op, type, evaluate, parsedArgs);\n }\n }\n if (overloads.length === 1) {\n context.errors.push(...signatureContext.errors);\n }\n else {\n const expected = overloads.length ? overloads : availableOverloads;\n const signatures = expected\n .map(([params]) => stringifySignature(params))\n .join(' | ');\n const actualTypes = [];\n // For error message, re-parse arguments without trying to\n // apply any coercions\n for (let i = 1; i < args.length; i++) {\n const parsed = context.parse(args[i], 1 + actualTypes.length);\n if (!parsed)\n return null;\n actualTypes.push(toString$1(parsed.type));\n }\n context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`);\n }\n return null;\n }\n static register(registry, definitions) {\n CompoundExpression.definitions = definitions;\n for (const name in definitions) {\n registry[name] = CompoundExpression;\n }\n }\n}\nfunction rgba(ctx, [r, g, b, a]) {\n r = r.evaluate(ctx);\n g = g.evaluate(ctx);\n b = b.evaluate(ctx);\n const alpha = a ? a.evaluate(ctx) : 1;\n const error = validateRGBA(r, g, b, alpha);\n if (error)\n throw new RuntimeError(error);\n return new Color(r / 255, g / 255, b / 255, alpha, false);\n}\nfunction has(key, obj) {\n return key in obj;\n}\nfunction get(key, obj) {\n const v = obj[key];\n return typeof v === 'undefined' ? null : v;\n}\nfunction binarySearch(v, a, i, j) {\n while (i <= j) {\n const m = (i + j) >> 1;\n if (a[m] === v)\n return true;\n if (a[m] > v)\n j = m - 1;\n else\n i = m + 1;\n }\n return false;\n}\nfunction varargs(type) {\n return { type };\n}\nCompoundExpression.register(expressions$1, {\n 'error': [\n ErrorType,\n [StringType],\n (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); }\n ],\n 'typeof': [\n StringType,\n [ValueType],\n (ctx, [v]) => toString$1(typeOf(v.evaluate(ctx)))\n ],\n 'to-rgba': [\n array$1(NumberType, 4),\n [ColorType],\n (ctx, [v]) => {\n const [r, g, b, a] = v.evaluate(ctx).rgb;\n return [r * 255, g * 255, b * 255, a];\n },\n ],\n 'rgb': [\n ColorType,\n [NumberType, NumberType, NumberType],\n rgba\n ],\n 'rgba': [\n ColorType,\n [NumberType, NumberType, NumberType, NumberType],\n rgba\n ],\n 'has': {\n type: BooleanType,\n overloads: [\n [\n [StringType],\n (ctx, [key]) => has(key.evaluate(ctx), ctx.properties())\n ], [\n [StringType, ObjectType],\n (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx))\n ]\n ]\n },\n 'get': {\n type: ValueType,\n overloads: [\n [\n [StringType],\n (ctx, [key]) => get(key.evaluate(ctx), ctx.properties())\n ], [\n [StringType, ObjectType],\n (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx))\n ]\n ]\n },\n 'feature-state': [\n ValueType,\n [StringType],\n (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {})\n ],\n 'properties': [\n ObjectType,\n [],\n (ctx) => ctx.properties()\n ],\n 'geometry-type': [\n StringType,\n [],\n (ctx) => ctx.geometryType()\n ],\n 'id': [\n ValueType,\n [],\n (ctx) => ctx.id()\n ],\n 'zoom': [\n NumberType,\n [],\n (ctx) => ctx.globals.zoom\n ],\n 'heatmap-density': [\n NumberType,\n [],\n (ctx) => ctx.globals.heatmapDensity || 0\n ],\n 'line-progress': [\n NumberType,\n [],\n (ctx) => ctx.globals.lineProgress || 0\n ],\n 'accumulated': [\n ValueType,\n [],\n (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated\n ],\n '+': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 0;\n for (const arg of args) {\n result += arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '*': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 1;\n for (const arg of args) {\n result *= arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '-': {\n type: NumberType,\n overloads: [\n [\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)\n ], [\n [NumberType],\n (ctx, [a]) => -a.evaluate(ctx)\n ]\n ]\n },\n '/': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx)\n ],\n '%': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx)\n ],\n 'ln2': [\n NumberType,\n [],\n () => Math.LN2\n ],\n 'pi': [\n NumberType,\n [],\n () => Math.PI\n ],\n 'e': [\n NumberType,\n [],\n () => Math.E\n ],\n '^': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx))\n ],\n 'sqrt': [\n NumberType,\n [NumberType],\n (ctx, [x]) => Math.sqrt(x.evaluate(ctx))\n ],\n 'log10': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10\n ],\n 'ln': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx))\n ],\n 'log2': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2\n ],\n 'sin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.sin(n.evaluate(ctx))\n ],\n 'cos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.cos(n.evaluate(ctx))\n ],\n 'tan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.tan(n.evaluate(ctx))\n ],\n 'asin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.asin(n.evaluate(ctx))\n ],\n 'acos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.acos(n.evaluate(ctx))\n ],\n 'atan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.atan(n.evaluate(ctx))\n ],\n 'min': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'max': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'abs': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.abs(n.evaluate(ctx))\n ],\n 'round': [\n NumberType,\n [NumberType],\n (ctx, [n]) => {\n const v = n.evaluate(ctx);\n // Javascript's Math.round() rounds towards +Infinity for halfway\n // values, even when they're negative. It's more common to round\n // away from 0 (e.g., this is what python and C++ do)\n return v < 0 ? -Math.round(-v) : Math.round(v);\n }\n ],\n 'floor': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.floor(n.evaluate(ctx))\n ],\n 'ceil': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.ceil(n.evaluate(ctx))\n ],\n 'filter-==': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => ctx.properties()[k.value] === v.value\n ],\n 'filter-id-==': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => ctx.id() === v.value\n ],\n 'filter-type-==': [\n BooleanType,\n [StringType],\n (ctx, [v]) => ctx.geometryType() === v.value\n ],\n 'filter-<': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[k.value];\n const b = v.value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter-id-<': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = v.value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter->': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[k.value];\n const b = v.value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-id->': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = v.value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-<=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[k.value];\n const b = v.value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter-id-<=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = v.value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter->=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[k.value];\n const b = v.value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-id->=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = v.value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-has': [\n BooleanType,\n [ValueType],\n (ctx, [k]) => k.value in ctx.properties()\n ],\n 'filter-has-id': [\n BooleanType,\n [],\n (ctx) => (ctx.id() !== null && ctx.id() !== undefined)\n ],\n 'filter-type-in': [\n BooleanType,\n [array$1(StringType)],\n (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0\n ],\n 'filter-id-in': [\n BooleanType,\n [array$1(ValueType)],\n (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0\n ],\n 'filter-in-small': [\n BooleanType,\n [StringType, array$1(ValueType)],\n // assumes v is an array literal\n (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0\n ],\n 'filter-in-large': [\n BooleanType,\n [StringType, array$1(ValueType)],\n // assumes v is a array literal with values sorted in ascending order and of a single type\n (ctx, [k, v]) => binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1)\n ],\n 'all': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (!arg.evaluate(ctx))\n return false;\n }\n return true;\n }\n ]\n ]\n },\n 'any': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (arg.evaluate(ctx))\n return true;\n }\n return false;\n }\n ]\n ]\n },\n '!': [\n BooleanType,\n [BooleanType],\n (ctx, [b]) => !b.evaluate(ctx)\n ],\n 'is-supported-script': [\n BooleanType,\n [StringType],\n // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant\n (ctx, [s]) => {\n const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;\n if (isSupportedScript) {\n return isSupportedScript(s.evaluate(ctx));\n }\n return true;\n }\n ],\n 'upcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toUpperCase()\n ],\n 'downcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toLowerCase()\n ],\n 'concat': [\n StringType,\n varargs(ValueType),\n (ctx, args) => args.map(arg => toString(arg.evaluate(ctx))).join('')\n ],\n 'resolved-locale': [\n StringType,\n [CollatorType],\n (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()\n ]\n});\nfunction stringifySignature(signature) {\n if (Array.isArray(signature)) {\n return `(${signature.map(toString$1).join(', ')})`;\n }\n else {\n return `(${toString$1(signature.type)}...)`;\n }\n}\nfunction isExpressionConstant(expression) {\n if (expression instanceof Var) {\n return isExpressionConstant(expression.boundExpression);\n }\n else if (expression instanceof CompoundExpression && expression.name === 'error') {\n return false;\n }\n else if (expression instanceof CollatorExpression) {\n // Although the results of a Collator expression with fixed arguments\n // generally shouldn't change between executions, we can't serialize them\n // as constant expressions because results change based on environment.\n return false;\n }\n else if (expression instanceof Within) {\n return false;\n }\n else if (expression instanceof Distance) {\n return false;\n }\n const isTypeAnnotation = expression instanceof Coercion ||\n expression instanceof Assertion;\n let childrenConstant = true;\n expression.eachChild(child => {\n // We can _almost_ assume that if `expressions` children are constant,\n // they would already have been evaluated to Literal values when they\n // were parsed. Type annotations are the exception, because they might\n // have been inferred and added after a child was parsed.\n // So we recurse into isConstant() for the children of type annotations,\n // but otherwise simply check whether they are Literals.\n if (isTypeAnnotation) {\n childrenConstant = childrenConstant && isExpressionConstant(child);\n }\n else {\n childrenConstant = childrenConstant && child instanceof Literal;\n }\n });\n if (!childrenConstant) {\n return false;\n }\n return isFeatureConstant(expression) &&\n isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']);\n}\nfunction isFeatureConstant(e) {\n if (e instanceof CompoundExpression) {\n if (e.name === 'get' && e.args.length === 1) {\n return false;\n }\n else if (e.name === 'feature-state') {\n return false;\n }\n else if (e.name === 'has' && e.args.length === 1) {\n return false;\n }\n else if (e.name === 'properties' ||\n e.name === 'geometry-type' ||\n e.name === 'id') {\n return false;\n }\n else if (/^filter-/.test(e.name)) {\n return false;\n }\n }\n if (e instanceof Within) {\n return false;\n }\n if (e instanceof Distance) {\n return false;\n }\n let result = true;\n e.eachChild(arg => {\n if (result && !isFeatureConstant(arg)) {\n result = false;\n }\n });\n return result;\n}\nfunction isStateConstant(e) {\n if (e instanceof CompoundExpression) {\n if (e.name === 'feature-state') {\n return false;\n }\n }\n let result = true;\n e.eachChild(arg => {\n if (result && !isStateConstant(arg)) {\n result = false;\n }\n });\n return result;\n}\nfunction isGlobalPropertyConstant(e, properties) {\n if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) {\n return false;\n }\n let result = true;\n e.eachChild((arg) => {\n if (result && !isGlobalPropertyConstant(arg, properties)) {\n result = false;\n }\n });\n return result;\n}\n\nfunction success(value) {\n return { result: 'success', value };\n}\nfunction error(value) {\n return { result: 'error', value };\n}\n\nfunction supportsPropertyExpression(spec) {\n return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven';\n}\nfunction supportsZoomExpression(spec) {\n return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1;\n}\nfunction supportsInterpolation(spec) {\n return !!spec.expression && spec.expression.interpolated;\n}\n\nfunction getType(val) {\n if (val instanceof Number) {\n return 'number';\n }\n else if (val instanceof String) {\n return 'string';\n }\n else if (val instanceof Boolean) {\n return 'boolean';\n }\n else if (Array.isArray(val)) {\n return 'array';\n }\n else if (val === null) {\n return 'null';\n }\n else {\n return typeof val;\n }\n}\n\nfunction isFunction$1(value) {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\nfunction identityFunction(x) {\n return x;\n}\nfunction createFunction(parameters, propertySpec) {\n const isColor = propertySpec.type === 'color';\n const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object';\n const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined;\n const zoomDependent = zoomAndFeatureDependent || !featureDependent;\n const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval');\n if (isColor || propertySpec.type === 'padding') {\n const parseFn = isColor ? Color.parse : Padding.parse;\n parameters = extendBy({}, parameters);\n if (parameters.stops) {\n parameters.stops = parameters.stops.map((stop) => {\n return [stop[0], parseFn(stop[1])];\n });\n }\n if (parameters.default) {\n parameters.default = parseFn(parameters.default);\n }\n else {\n parameters.default = parseFn(propertySpec.default);\n }\n }\n if (parameters.colorSpace && !isSupportedInterpolationColorSpace(parameters.colorSpace)) {\n throw new Error(`Unknown color space: \"${parameters.colorSpace}\"`);\n }\n let innerFun;\n let hashedStops;\n let categoricalKeyType;\n if (type === 'exponential') {\n innerFun = evaluateExponentialFunction;\n }\n else if (type === 'interval') {\n innerFun = evaluateIntervalFunction;\n }\n else if (type === 'categorical') {\n innerFun = evaluateCategoricalFunction;\n // For categorical functions, generate an Object as a hashmap of the stops for fast searching\n hashedStops = Object.create(null);\n for (const stop of parameters.stops) {\n hashedStops[stop[0]] = stop[1];\n }\n // Infer key type based on first stop key-- used to encforce strict type checking later\n categoricalKeyType = typeof parameters.stops[0][0];\n }\n else if (type === 'identity') {\n innerFun = evaluateIdentityFunction;\n }\n else {\n throw new Error(`Unknown function type \"${type}\"`);\n }\n if (zoomAndFeatureDependent) {\n const featureFunctions = {};\n const zoomStops = [];\n for (let s = 0; s < parameters.stops.length; s++) {\n const stop = parameters.stops[s];\n const zoom = stop[0].zoom;\n if (featureFunctions[zoom] === undefined) {\n featureFunctions[zoom] = {\n zoom,\n type: parameters.type,\n property: parameters.property,\n default: parameters.default,\n stops: []\n };\n zoomStops.push(zoom);\n }\n featureFunctions[zoom].stops.push([stop[0].value, stop[1]]);\n }\n const featureFunctionStops = [];\n for (const z of zoomStops) {\n featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]);\n }\n const interpolationType = { name: 'linear' };\n return {\n kind: 'composite',\n interpolationType,\n interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType),\n zoomStops: featureFunctionStops.map(s => s[0]),\n evaluate({ zoom }, properties) {\n return evaluateExponentialFunction({\n stops: featureFunctionStops,\n base: parameters.base\n }, propertySpec, zoom).evaluate(zoom, properties);\n }\n };\n }\n else if (zoomDependent) {\n const interpolationType = type === 'exponential' ?\n { name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1 } : null;\n return {\n kind: 'camera',\n interpolationType,\n interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType),\n zoomStops: parameters.stops.map(s => s[0]),\n evaluate: ({ zoom }) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType)\n };\n }\n else {\n return {\n kind: 'source',\n evaluate(_, feature) {\n const value = feature && feature.properties ? feature.properties[parameters.property] : undefined;\n if (value === undefined) {\n return coalesce$1(parameters.default, propertySpec.default);\n }\n return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType);\n }\n };\n }\n}\nfunction coalesce$1(a, b, c) {\n if (a !== undefined)\n return a;\n if (b !== undefined)\n return b;\n if (c !== undefined)\n return c;\n}\nfunction evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) {\n const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input\n return coalesce$1(evaluated, parameters.default, propertySpec.default);\n}\nfunction evaluateIntervalFunction(parameters, propertySpec, input) {\n // Edge cases\n if (getType(input) !== 'number')\n return coalesce$1(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1)\n return parameters.stops[0][1];\n if (input <= parameters.stops[0][0])\n return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0])\n return parameters.stops[n - 1][1];\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n return parameters.stops[index][1];\n}\nfunction evaluateExponentialFunction(parameters, propertySpec, input) {\n const base = parameters.base !== undefined ? parameters.base : 1;\n // Edge cases\n if (getType(input) !== 'number')\n return coalesce$1(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1)\n return parameters.stops[0][1];\n if (input <= parameters.stops[0][0])\n return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0])\n return parameters.stops[n - 1][1];\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n const t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]);\n const outputLower = parameters.stops[index][1];\n const outputUpper = parameters.stops[index + 1][1];\n const interp = interpolate[propertySpec.type] || identityFunction;\n if (typeof outputLower.evaluate === 'function') {\n return {\n evaluate(...args) {\n const evaluatedLower = outputLower.evaluate.apply(undefined, args);\n const evaluatedUpper = outputUpper.evaluate.apply(undefined, args);\n // Special case for fill-outline-color, which has no spec default.\n if (evaluatedLower === undefined || evaluatedUpper === undefined) {\n return undefined;\n }\n return interp(evaluatedLower, evaluatedUpper, t, parameters.colorSpace);\n }\n };\n }\n return interp(outputLower, outputUpper, t, parameters.colorSpace);\n}\nfunction evaluateIdentityFunction(parameters, propertySpec, input) {\n switch (propertySpec.type) {\n case 'color':\n input = Color.parse(input);\n break;\n case 'formatted':\n input = Formatted.fromString(input.toString());\n break;\n case 'resolvedImage':\n input = ResolvedImage.fromString(input.toString());\n break;\n case 'padding':\n input = Padding.parse(input);\n break;\n default:\n if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) {\n input = undefined;\n }\n }\n return coalesce$1(input, parameters.default, propertySpec.default);\n}\n/**\n * Returns a ratio that can be used to interpolate between exponential function\n * stops.\n *\n * How it works:\n * Two consecutive stop values define a (scaled and shifted) exponential\n * function `f(x) = a * base^x + b`, where `base` is the user-specified base,\n * and `a` and `b` are constants affording sufficient degrees of freedom to fit\n * the function to the given stops.\n *\n * Here's a bit of algebra that lets us compute `f(x)` directly from the stop\n * values without explicitly solving for `a` and `b`:\n *\n * First stop value: `f(x0) = y0 = a * base^x0 + b`\n * Second stop value: `f(x1) = y1 = a * base^x1 + b`\n * => `y1 - y0 = a(base^x1 - base^x0)`\n * => `a = (y1 - y0)/(base^x1 - base^x0)`\n *\n * Desired value: `f(x) = y = a * base^x + b`\n * => `f(x) = y0 + a * (base^x - base^x0)`\n *\n * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a\n * little algebra:\n * ```\n * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)\n * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)\n * ```\n *\n * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have\n * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as\n * an interpolation factor between the two stops' output values.\n *\n * (Note: a slightly different form for `ratio`,\n * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer\n * expensive `Math.pow()` operations.)\n *\n * @private\n */\nfunction interpolationFactor(input, base, lowerValue, upperValue) {\n const difference = upperValue - lowerValue;\n const progress = input - lowerValue;\n if (difference === 0) {\n return 0;\n }\n else if (base === 1) {\n return progress / difference;\n }\n else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n\nclass StyleExpression {\n constructor(expression, propertySpec) {\n this.expression = expression;\n this._warningHistory = {};\n this._evaluator = new EvaluationContext();\n this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;\n this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;\n }\n evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature;\n this._evaluator.featureState = featureState;\n this._evaluator.canonical = canonical;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection;\n return this.expression.evaluate(this._evaluator);\n }\n evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature || null;\n this._evaluator.featureState = featureState || null;\n this._evaluator.canonical = canonical;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection || null;\n try {\n const val = this.expression.evaluate(this._evaluator);\n // eslint-disable-next-line no-self-compare\n if (val === null || val === undefined || (typeof val === 'number' && val !== val)) {\n return this._defaultValue;\n }\n if (this._enumValues && !(val in this._enumValues)) {\n throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ')}, but found ${JSON.stringify(val)} instead.`);\n }\n return val;\n }\n catch (e) {\n if (!this._warningHistory[e.message]) {\n this._warningHistory[e.message] = true;\n if (typeof console !== 'undefined') {\n console.warn(e.message);\n }\n }\n return this._defaultValue;\n }\n }\n}\nfunction isExpression(expression) {\n return Array.isArray(expression) && expression.length > 0 &&\n typeof expression[0] === 'string' && expression[0] in expressions$1;\n}\n/**\n * Parse and typecheck the given style spec JSON expression. If\n * options.defaultValue is provided, then the resulting StyleExpression's\n * `evaluate()` method will handle errors by logging a warning (once per\n * message) and returning the default value. Otherwise, it will throw\n * evaluation errors.\n *\n * @private\n */\nfunction createExpression(expression, propertySpec) {\n const parser = new ParsingContext(expressions$1, isExpressionConstant, [], propertySpec ? getExpectedType(propertySpec) : undefined);\n // For string-valued properties, coerce to string at the top level rather than asserting.\n const parsed = parser.parse(expression, undefined, undefined, undefined, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : undefined);\n if (!parsed) {\n return error(parser.errors);\n }\n return success(new StyleExpression(parsed, propertySpec));\n}\nclass ZoomConstantExpression {\n constructor(kind, expression) {\n this.kind = kind;\n this._styleExpression = expression;\n this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression);\n }\n evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n}\nclass ZoomDependentExpression {\n constructor(kind, expression, zoomStops, interpolationType) {\n this.kind = kind;\n this.zoomStops = zoomStops;\n this._styleExpression = expression;\n this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression);\n this.interpolationType = interpolationType;\n }\n evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n interpolationFactor(input, lower, upper) {\n if (this.interpolationType) {\n return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);\n }\n else {\n return 0;\n }\n }\n}\nfunction isZoomExpression(expression) {\n return expression._styleExpression !== undefined;\n}\nfunction createPropertyExpression(expressionInput, propertySpec) {\n const expression = createExpression(expressionInput, propertySpec);\n if (expression.result === 'error') {\n return expression;\n }\n const parsed = expression.value.expression;\n const isFeatureConstantResult = isFeatureConstant(parsed);\n if (!isFeatureConstantResult && !supportsPropertyExpression(propertySpec)) {\n return error([new ExpressionParsingError('', 'data expressions not supported')]);\n }\n const isZoomConstant = isGlobalPropertyConstant(parsed, ['zoom']);\n if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {\n return error([new ExpressionParsingError('', 'zoom expressions not supported')]);\n }\n const zoomCurve = findZoomCurve(parsed);\n if (!zoomCurve && !isZoomConstant) {\n return error([new ExpressionParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.')]);\n }\n else if (zoomCurve instanceof ExpressionParsingError) {\n return error([zoomCurve]);\n }\n else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) {\n return error([new ExpressionParsingError('', '\"interpolate\" expressions cannot be used with this property')]);\n }\n if (!zoomCurve) {\n return success(isFeatureConstantResult ?\n new ZoomConstantExpression('constant', expression.value) :\n new ZoomConstantExpression('source', expression.value));\n }\n const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined;\n return success(isFeatureConstantResult ?\n new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType) :\n new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType));\n}\n// serialization wrapper for old-style stop functions normalized to the\n// expression interface\nclass StylePropertyFunction {\n constructor(parameters, specification) {\n this._parameters = parameters;\n this._specification = specification;\n extendBy(this, createFunction(this._parameters, this._specification));\n }\n static deserialize(serialized) {\n return new StylePropertyFunction(serialized._parameters, serialized._specification);\n }\n static serialize(input) {\n return {\n _parameters: input._parameters,\n _specification: input._specification\n };\n }\n}\nfunction normalizePropertyExpression(value, specification) {\n if (isFunction$1(value)) {\n return new StylePropertyFunction(value, specification);\n }\n else if (isExpression(value)) {\n const expression = createPropertyExpression(value, specification);\n if (expression.result === 'error') {\n // this should have been caught in validation\n throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', '));\n }\n return expression.value;\n }\n else {\n let constant = value;\n if (specification.type === 'color' && typeof value === 'string') {\n constant = Color.parse(value);\n }\n else if (specification.type === 'padding' && (typeof value === 'number' || Array.isArray(value))) {\n constant = Padding.parse(value);\n }\n else if (specification.type === 'variableAnchorOffsetCollection' && Array.isArray(value)) {\n constant = VariableAnchorOffsetCollection.parse(value);\n }\n return {\n kind: 'constant',\n evaluate: () => constant\n };\n }\n}\n// Zoom-dependent expressions may only use [\"zoom\"] as the input to a top-level \"step\" or \"interpolate\"\n// expression (collectively referred to as a \"curve\"). The curve may be wrapped in one or more \"let\" or\n// \"coalesce\" expressions.\nfunction findZoomCurve(expression) {\n let result = null;\n if (expression instanceof Let) {\n result = findZoomCurve(expression.result);\n }\n else if (expression instanceof Coalesce) {\n for (const arg of expression.args) {\n result = findZoomCurve(arg);\n if (result) {\n break;\n }\n }\n }\n else if ((expression instanceof Step || expression instanceof Interpolate) &&\n expression.input instanceof CompoundExpression &&\n expression.input.name === 'zoom') {\n result = expression;\n }\n if (result instanceof ExpressionParsingError) {\n return result;\n }\n expression.eachChild((child) => {\n const childResult = findZoomCurve(child);\n if (childResult instanceof ExpressionParsingError) {\n result = childResult;\n }\n else if (!result && childResult) {\n result = new ExpressionParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.');\n }\n else if (result && childResult && result !== childResult) {\n result = new ExpressionParsingError('', 'Only one zoom-based \"step\" or \"interpolate\" subexpression may be used in an expression.');\n }\n });\n return result;\n}\nfunction getExpectedType(spec) {\n const types = {\n color: ColorType,\n string: StringType,\n number: NumberType,\n enum: StringType,\n boolean: BooleanType,\n formatted: FormattedType,\n padding: PaddingType,\n resolvedImage: ResolvedImageType,\n variableAnchorOffsetCollection: VariableAnchorOffsetCollectionType\n };\n if (spec.type === 'array') {\n return array$1(types[spec.value] || ValueType, spec.length);\n }\n return types[spec.type];\n}\nfunction getDefaultValue(spec) {\n if (spec.type === 'color' && isFunction$1(spec.default)) {\n // Special case for heatmap-color: it uses the 'default:' to define a\n // default color ramp, but createExpression expects a simple value to fall\n // back to in case of runtime errors\n return new Color(0, 0, 0, 0);\n }\n else if (spec.type === 'color') {\n return Color.parse(spec.default) || null;\n }\n else if (spec.type === 'padding') {\n return Padding.parse(spec.default) || null;\n }\n else if (spec.type === 'variableAnchorOffsetCollection') {\n return VariableAnchorOffsetCollection.parse(spec.default) || null;\n }\n else if (spec.default === undefined) {\n return null;\n }\n else {\n return spec.default;\n }\n}\n\nfunction isExpressionFilter(filter) {\n if (filter === true || filter === false) {\n return true;\n }\n if (!Array.isArray(filter) || filter.length === 0) {\n return false;\n }\n switch (filter[0]) {\n case 'has':\n return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type';\n case 'in':\n return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2]));\n case '!in':\n case '!has':\n case 'none':\n return false;\n case '==':\n case '!=':\n case '>':\n case '>=':\n case '<':\n case '<=':\n return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2]));\n case 'any':\n case 'all':\n for (const f of filter.slice(1)) {\n if (!isExpressionFilter(f) && typeof f !== 'boolean') {\n return false;\n }\n }\n return true;\n default:\n return true;\n }\n}\nconst filterSpec = {\n 'type': 'boolean',\n 'default': false,\n 'transition': false,\n 'property-type': 'data-driven',\n 'expression': {\n 'interpolated': false,\n 'parameters': ['zoom', 'feature']\n }\n};\n/**\n * Given a filter expressed as nested arrays, return a new function\n * that evaluates whether a given feature (with a .properties or .tags property)\n * passes its test.\n *\n * @private\n * @param {Array} filter MapLibre filter\n * @returns {Function} filter-evaluating function\n */\nfunction createFilter(filter) {\n if (filter === null || filter === undefined) {\n return { filter: () => true, needGeometry: false };\n }\n if (!isExpressionFilter(filter)) {\n filter = convertFilter$1(filter);\n }\n const compiled = createExpression(filter, filterSpec);\n if (compiled.result === 'error') {\n throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));\n }\n else {\n const needGeometry = geometryNeeded(filter);\n return { filter: (globalProperties, feature, canonical) => compiled.value.evaluate(globalProperties, feature, {}, canonical),\n needGeometry };\n }\n}\n// Comparison function to sort numbers and strings\nfunction compare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\nfunction geometryNeeded(filter) {\n if (!Array.isArray(filter))\n return false;\n if (filter[0] === 'within' || filter[0] === 'distance')\n return true;\n for (let index = 1; index < filter.length; index++) {\n if (geometryNeeded(filter[index]))\n return true;\n }\n return false;\n}\nfunction convertFilter$1(filter) {\n if (!filter)\n return true;\n const op = filter[0];\n if (filter.length <= 1)\n return (op !== 'any');\n const converted = op === '==' ? convertComparisonOp$1(filter[1], filter[2], '==') :\n op === '!=' ? convertNegation(convertComparisonOp$1(filter[1], filter[2], '==')) :\n op === '<' ||\n op === '>' ||\n op === '<=' ||\n op === '>=' ? convertComparisonOp$1(filter[1], filter[2], op) :\n op === 'any' ? convertDisjunctionOp(filter.slice(1)) :\n op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter$1)) :\n op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter$1).map(convertNegation)) :\n op === 'in' ? convertInOp$1(filter[1], filter.slice(2)) :\n op === '!in' ? convertNegation(convertInOp$1(filter[1], filter.slice(2))) :\n op === 'has' ? convertHasOp$1(filter[1]) :\n op === '!has' ? convertNegation(convertHasOp$1(filter[1])) :\n true;\n return converted;\n}\nfunction convertComparisonOp$1(property, value, op) {\n switch (property) {\n case '$type':\n return [`filter-type-${op}`, value];\n case '$id':\n return [`filter-id-${op}`, value];\n default:\n return [`filter-${op}`, property, value];\n }\n}\nfunction convertDisjunctionOp(filters) {\n return ['any'].concat(filters.map(convertFilter$1));\n}\nfunction convertInOp$1(property, values) {\n if (values.length === 0) {\n return false;\n }\n switch (property) {\n case '$type':\n return ['filter-type-in', ['literal', values]];\n case '$id':\n return ['filter-id-in', ['literal', values]];\n default:\n if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) {\n return ['filter-in-large', property, ['literal', values.sort(compare)]];\n }\n else {\n return ['filter-in-small', property, ['literal', values]];\n }\n }\n}\nfunction convertHasOp$1(property) {\n switch (property) {\n case '$type':\n return true;\n case '$id':\n return ['filter-has-id'];\n default:\n return ['filter-has', property];\n }\n}\nfunction convertNegation(filter) {\n return ['!', filter];\n}\n\n/*\n * Convert the given filter to an expression, storing the expected types for\n * any feature properties referenced in expectedTypes.\n *\n * These expected types are needed in order to construct preflight type checks\n * needed for handling 'any' filters. A preflight type check is necessary in\n * order to mimic legacy filters' semantics around expected type mismatches.\n * For example, consider the legacy filter:\n *\n * [\"any\", [\"all\", [\">\", \"y\", 0], [\">\", \"y\", 0]], [\">\", \"x\", 0]]\n *\n * Naively, we might convert this to the expression:\n *\n * [\"any\", [\"all\", [\">\", [\"get\", \"y\"], 0], [\">\", [\"get\", \"z\"], 0]], [\">\", [\"get\", \"x\"], 0]]\n *\n * But if we tried to evaluate this against, say `{x: 1, y: null, z: 0}`, the\n * [\">\", [\"get\", \"y\"], 0] would cause an evaluation error, leading to the\n * entire filter returning false. Legacy filter semantics, though, ask for\n * [\">\", \"y\", 0] to simply return `false` when `y` is of the wrong type,\n * allowing the subsequent terms of the outer \"any\" expression to be evaluated\n * (resulting, in this case, in a `true` value, because x > 0).\n *\n * We account for this by inserting a preflight type-checking expression before\n * each \"any\" term, allowing us to avoid evaluating the actual converted filter\n * if any type mismatches would cause it to produce an evalaution error:\n *\n * [\"any\",\n * [\"case\",\n * [\"all\", [\"==\", [\"typeof\", [\"get\", \"y\"]], \"number\"], [\"==\", [\"typeof\", [\"get\", \"z\"], \"number]],\n * [\"all\", [\">\", [\"get\", \"y\"], 0], [\">\", [\"get\", \"z\"], 0]],\n * false\n * ],\n * [\"case\",\n * [\"==\", [\"typeof\", [\"get\", \"x\"], \"number\"]],\n * [\">\", [\"get\", \"x\"], 0],\n * false\n * ]\n * ]\n *\n * An alternative, possibly more direct approach would be to use type checks\n * in the conversion of each comparison operator, so that the converted version\n * of each individual ==, >=, etc. would mimic the legacy filter semantics. The\n * downside of this approach is that it can lead to many more type checks than\n * would otherwise be necessary: outside the context of an \"any\" expression,\n * bailing out due to a runtime type error (expression semantics) and returning\n * false (legacy filter semantics) are equivalent: they cause the filter to\n * produce a `false` result.\n */\nfunction convertFilter(filter, expectedTypes = {}) {\n if (isExpressionFilter(filter))\n return filter;\n if (!filter)\n return true;\n const legacyFilter = filter;\n const legacyOp = legacyFilter[0];\n if (filter.length <= 1)\n return (legacyOp !== 'any');\n switch (legacyOp) {\n case '==':\n case '!=':\n case '<':\n case '>':\n case '<=':\n case '>=': {\n const [, property, value] = filter;\n return convertComparisonOp(property, value, legacyOp, expectedTypes);\n }\n case 'any': {\n const [, ...conditions] = legacyFilter;\n const children = conditions.map((f) => {\n const types = {};\n const child = convertFilter(f, types);\n const typechecks = runtimeTypeChecks(types);\n return typechecks === true ? child : ['case', typechecks, child, false];\n });\n return ['any', ...children];\n }\n case 'all': {\n const [, ...conditions] = legacyFilter;\n const children = conditions.map(f => convertFilter(f, expectedTypes));\n return children.length > 1 ? ['all', ...children] : children[0];\n }\n case 'none': {\n const [, ...conditions] = legacyFilter;\n return ['!', convertFilter(['any', ...conditions], {})];\n }\n case 'in': {\n const [, property, ...values] = legacyFilter;\n return convertInOp(property, values);\n }\n case '!in': {\n const [, property, ...values] = legacyFilter;\n return convertInOp(property, values, true);\n }\n case 'has':\n return convertHasOp(legacyFilter[1]);\n case '!has':\n return ['!', convertHasOp(legacyFilter[1])];\n default:\n return true;\n }\n}\n// Given a set of feature properties and an expected type for each one,\n// construct an boolean expression that tests whether each property has the\n// right type.\n// E.g.: for {name: 'string', population: 'number'}, return\n// [ 'all',\n// ['==', ['typeof', ['get', 'name'], 'string']],\n// ['==', ['typeof', ['get', 'population'], 'number]]\n// ]\nfunction runtimeTypeChecks(expectedTypes) {\n const conditions = [];\n for (const property in expectedTypes) {\n const get = property === '$id' ? ['id'] : ['get', property];\n conditions.push(['==', ['typeof', get], expectedTypes[property]]);\n }\n if (conditions.length === 0)\n return true;\n if (conditions.length === 1)\n return conditions[0];\n return ['all', ...conditions];\n}\nfunction convertComparisonOp(property, value, op, expectedTypes) {\n let get;\n if (property === '$type') {\n return [op, ['geometry-type'], value];\n }\n else if (property === '$id') {\n get = ['id'];\n }\n else {\n get = ['get', property];\n }\n if (expectedTypes && value !== null) {\n const type = typeof value;\n expectedTypes[property] = type;\n }\n if (op === '==' && property !== '$id' && value === null) {\n return [\n 'all',\n ['has', property], // missing property != null for legacy filters\n ['==', get, null]\n ];\n }\n else if (op === '!=' && property !== '$id' && value === null) {\n return [\n 'any',\n ['!', ['has', property]], // missing property != null for legacy filters\n ['!=', get, null]\n ];\n }\n return [op, get, value];\n}\nfunction convertInOp(property, values, negate = false) {\n if (values.length === 0)\n return negate;\n let get;\n if (property === '$type') {\n get = ['geometry-type'];\n }\n else if (property === '$id') {\n get = ['id'];\n }\n else {\n get = ['get', property];\n }\n // Determine if the list of values to be searched is homogenously typed.\n // If so (and if the type is string or number), then we can use a\n // [match, input, [...values], true, false] construction rather than a\n // bunch of `==` tests.\n let uniformTypes = true;\n const type = typeof values[0];\n for (const value of values) {\n if (typeof value !== type) {\n uniformTypes = false;\n break;\n }\n }\n if (uniformTypes && (type === 'string' || type === 'number')) {\n // Match expressions must have unique values.\n const uniqueValues = values.sort().filter((v, i) => i === 0 || values[i - 1] !== v);\n return ['match', get, uniqueValues, !negate, negate];\n }\n if (negate) {\n return ['all', ...values.map(v => ['!=', get, v])];\n }\n else {\n return ['any', ...values.map(v => ['==', get, v])];\n }\n}\nfunction convertHasOp(property) {\n if (property === '$type') {\n return true;\n }\n else if (property === '$id') {\n return ['!=', ['id'], null];\n }\n else {\n return ['has', property];\n }\n}\n\nfunction convertLiteral(value) {\n return typeof value === 'object' ? ['literal', value] : value;\n}\nfunction convertFunction(parameters, propertySpec) {\n let stops = parameters.stops;\n if (!stops) {\n // identity function\n return convertIdentityFunction(parameters, propertySpec);\n }\n const zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object';\n const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined;\n const zoomDependent = zoomAndFeatureDependent || !featureDependent;\n stops = stops.map((stop) => {\n if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') {\n return [stop[0], convertTokenString(stop[1])];\n }\n return [stop[0], convertLiteral(stop[1])];\n });\n if (zoomAndFeatureDependent) {\n return convertZoomAndPropertyFunction(parameters, propertySpec, stops);\n }\n else if (zoomDependent) {\n return convertZoomFunction(parameters, propertySpec, stops);\n }\n else {\n return convertPropertyFunction(parameters, propertySpec, stops);\n }\n}\nfunction convertIdentityFunction(parameters, propertySpec) {\n const get = ['get', parameters.property];\n if (parameters.default === undefined) {\n // By default, expressions for string-valued properties get coerced. To preserve\n // legacy function semantics, insert an explicit assertion instead.\n return propertySpec.type === 'string' ? ['string', get] : get;\n }\n else if (propertySpec.type === 'enum') {\n return [\n 'match',\n get,\n Object.keys(propertySpec.values),\n get,\n parameters.default\n ];\n }\n else {\n const expression = [propertySpec.type === 'color' ? 'to-color' : propertySpec.type, get, convertLiteral(parameters.default)];\n if (propertySpec.type === 'array') {\n expression.splice(1, 0, propertySpec.value, propertySpec.length || null);\n }\n return expression;\n }\n}\nfunction getInterpolateOperator(parameters) {\n switch (parameters.colorSpace) {\n case 'hcl': return 'interpolate-hcl';\n case 'lab': return 'interpolate-lab';\n default: return 'interpolate';\n }\n}\nfunction convertZoomAndPropertyFunction(parameters, propertySpec, stops) {\n const featureFunctionParameters = {};\n const featureFunctionStops = {};\n const zoomStops = [];\n for (let s = 0; s < stops.length; s++) {\n const stop = stops[s];\n const zoom = stop[0].zoom;\n if (featureFunctionParameters[zoom] === undefined) {\n featureFunctionParameters[zoom] = {\n zoom,\n type: parameters.type,\n property: parameters.property,\n default: parameters.default,\n };\n featureFunctionStops[zoom] = [];\n zoomStops.push(zoom);\n }\n featureFunctionStops[zoom].push([stop[0].value, stop[1]]);\n }\n // the interpolation type for the zoom dimension of a zoom-and-property\n // function is determined directly from the style property specification\n // for which it's being used: linear for interpolatable properties, step\n // otherwise.\n const functionType = getFunctionType({}, propertySpec);\n if (functionType === 'exponential') {\n const expression = [getInterpolateOperator(parameters), ['linear'], ['zoom']];\n for (const z of zoomStops) {\n const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]);\n appendStopPair(expression, z, output, false);\n }\n return expression;\n }\n else {\n const expression = ['step', ['zoom']];\n for (const z of zoomStops) {\n const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]);\n appendStopPair(expression, z, output, true);\n }\n fixupDegenerateStepCurve(expression);\n return expression;\n }\n}\nfunction coalesce(a, b) {\n if (a !== undefined)\n return a;\n if (b !== undefined)\n return b;\n}\nfunction getFallback(parameters, propertySpec) {\n const defaultValue = convertLiteral(coalesce(parameters.default, propertySpec.default));\n /*\n * Some fields with type: resolvedImage have an undefined default.\n * Because undefined is an invalid value for resolvedImage, set fallback to\n * an empty string instead of undefined to ensure output\n * passes validation.\n */\n if (defaultValue === undefined && propertySpec.type === 'resolvedImage') {\n return '';\n }\n return defaultValue;\n}\nfunction convertPropertyFunction(parameters, propertySpec, stops) {\n const type = getFunctionType(parameters, propertySpec);\n const get = ['get', parameters.property];\n if (type === 'categorical' && typeof stops[0][0] === 'boolean') {\n const expression = ['case'];\n for (const stop of stops) {\n expression.push(['==', get, stop[0]], stop[1]);\n }\n expression.push(getFallback(parameters, propertySpec));\n return expression;\n }\n else if (type === 'categorical') {\n const expression = ['match', get];\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], false);\n }\n expression.push(getFallback(parameters, propertySpec));\n return expression;\n }\n else if (type === 'interval') {\n const expression = ['step', ['number', get]];\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], true);\n }\n fixupDegenerateStepCurve(expression);\n return parameters.default === undefined ? expression : [\n 'case',\n ['==', ['typeof', get], 'number'],\n expression,\n convertLiteral(parameters.default)\n ];\n }\n else if (type === 'exponential') {\n const base = parameters.base !== undefined ? parameters.base : 1;\n const expression = [\n getInterpolateOperator(parameters),\n base === 1 ? ['linear'] : ['exponential', base],\n ['number', get]\n ];\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], false);\n }\n return parameters.default === undefined ? expression : [\n 'case',\n ['==', ['typeof', get], 'number'],\n expression,\n convertLiteral(parameters.default)\n ];\n }\n else {\n throw new Error(`Unknown property function type ${type}`);\n }\n}\nfunction convertZoomFunction(parameters, propertySpec, stops, input = ['zoom']) {\n const type = getFunctionType(parameters, propertySpec);\n let expression;\n let isStep = false;\n if (type === 'interval') {\n expression = ['step', input];\n isStep = true;\n }\n else if (type === 'exponential') {\n const base = parameters.base !== undefined ? parameters.base : 1;\n expression = [getInterpolateOperator(parameters), base === 1 ? ['linear'] : ['exponential', base], input];\n }\n else {\n throw new Error(`Unknown zoom function type \"${type}\"`);\n }\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], isStep);\n }\n fixupDegenerateStepCurve(expression);\n return expression;\n}\nfunction fixupDegenerateStepCurve(expression) {\n // degenerate step curve (i.e. a constant function): add a noop stop\n if (expression[0] === 'step' && expression.length === 3) {\n expression.push(0);\n expression.push(expression[3]);\n }\n}\nfunction appendStopPair(curve, input, output, isStep) {\n // Skip duplicate stop values. They were not validated for functions, but they are for expressions.\n // https://github.com/mapbox/mapbox-gl-js/issues/4107\n if (curve.length > 3 && input === curve[curve.length - 2]) {\n return;\n }\n // step curves don't get the first input value, as it is redundant.\n if (!(isStep && curve.length === 2)) {\n curve.push(input);\n }\n curve.push(output);\n}\nfunction getFunctionType(parameters, propertySpec) {\n if (parameters.type) {\n return parameters.type;\n }\n else {\n return propertySpec.expression.interpolated ? 'exponential' : 'interval';\n }\n}\n// \"String with {name} token\" => [\"concat\", \"String with \", [\"get\", \"name\"], \" token\"]\nfunction convertTokenString(s) {\n const result = ['concat'];\n const re = /{([^{}]+)}/g;\n let pos = 0;\n for (let match = re.exec(s); match !== null; match = re.exec(s)) {\n const literal = s.slice(pos, re.lastIndex - match[0].length);\n pos = re.lastIndex;\n if (literal.length > 0)\n result.push(literal);\n result.push(['get', match[1]]);\n }\n if (result.length === 1) {\n return s;\n }\n if (pos < s.length) {\n result.push(s.slice(pos));\n }\n else if (result.length === 2) {\n return ['to-string', result[1]];\n }\n return result;\n}\n\nfunction getPropertyReference(propertyName) {\n for (let i = 0; i < v8Spec.layout.length; i++) {\n for (const key in v8Spec[v8Spec.layout[i]]) {\n if (key === propertyName)\n return v8Spec[v8Spec.layout[i]][key];\n }\n }\n for (let i = 0; i < v8Spec.paint.length; i++) {\n for (const key in v8Spec[v8Spec.paint[i]]) {\n if (key === propertyName)\n return v8Spec[v8Spec.paint[i]][key];\n }\n }\n return null;\n}\nfunction eachSource(style, callback) {\n for (const k in style.sources) {\n callback(style.sources[k]);\n }\n}\nfunction eachLayer(style, callback) {\n for (const layer of style.layers) {\n callback(layer);\n }\n}\nfunction eachProperty(style, options, callback) {\n function inner(layer, propertyType) {\n const properties = layer[propertyType];\n if (!properties)\n return;\n Object.keys(properties).forEach((key) => {\n callback({\n path: [layer.id, propertyType, key],\n key,\n value: properties[key],\n reference: getPropertyReference(key),\n set(x) {\n properties[key] = x;\n }\n });\n });\n }\n eachLayer(style, (layer) => {\n if (options.paint) {\n inner(layer, 'paint');\n }\n if (options.layout) {\n inner(layer, 'layout');\n }\n });\n}\n\nfunction stringify$1(obj) {\n const type = typeof obj;\n if (type === 'number' || type === 'boolean' || type === 'string' || obj === undefined || obj === null)\n return JSON.stringify(obj);\n if (Array.isArray(obj)) {\n let str = '[';\n for (const val of obj) {\n str += `${stringify$1(val)},`;\n }\n return `${str}]`;\n }\n const keys = Object.keys(obj).sort();\n let str = '{';\n for (let i = 0; i < keys.length; i++) {\n str += `${JSON.stringify(keys[i])}:${stringify$1(obj[keys[i]])},`;\n }\n return `${str}}`;\n}\nfunction getKey(layer) {\n let key = '';\n for (const k of refProperties) {\n key += `/${stringify$1(layer[k])}`;\n }\n return key;\n}\n/**\n * Given an array of layers, return an array of arrays of layers where all\n * layers in each group have identical layout-affecting properties. These\n * are the properties that were formerly used by explicit `ref` mechanism\n * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom',\n * 'filter', and 'layout'.\n *\n * The input is not modified. The output layers are references to the\n * input layers.\n *\n * @private\n * @param {Array} layers\n * @param {Object} [cachedKeys] - an object to keep already calculated keys.\n * @returns {Array>}\n */\nfunction groupByLayout(layers, cachedKeys) {\n const groups = {};\n for (let i = 0; i < layers.length; i++) {\n const k = (cachedKeys && cachedKeys[layers[i].id]) || getKey(layers[i]);\n // update the cache if there is one\n if (cachedKeys)\n cachedKeys[layers[i].id] = k;\n let group = groups[k];\n if (!group) {\n group = groups[k] = [];\n }\n group.push(layers[i]);\n }\n const result = [];\n for (const k in groups) {\n result.push(groups[k]);\n }\n return result;\n}\n\nfunction emptyStyle() {\n const style = {};\n const version = v8Spec['$version'];\n for (const styleKey in v8Spec['$root']) {\n const spec = v8Spec['$root'][styleKey];\n if (spec.required) {\n let value = null;\n if (styleKey === 'version') {\n value = version;\n }\n else {\n if (spec.type === 'array') {\n value = [];\n }\n else {\n value = {};\n }\n }\n if (value != null) {\n style[styleKey] = value;\n }\n }\n }\n return style;\n}\n\nfunction validateConstants(options) {\n const key = options.key;\n const constants = options.value;\n if (constants) {\n return [new ValidationError(key, constants, 'constants have been deprecated as of v8')];\n }\n else {\n return [];\n }\n}\n\n// Turn jsonlint-lines-primitives objects into primitive objects\nfunction unbundle(value) {\n if (value instanceof Number || value instanceof String || value instanceof Boolean) {\n return value.valueOf();\n }\n else {\n return value;\n }\n}\nfunction deepUnbundle(value) {\n if (Array.isArray(value)) {\n return value.map(deepUnbundle);\n }\n else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) {\n const unbundledValue = {};\n for (const key in value) {\n unbundledValue[key] = deepUnbundle(value[key]);\n }\n return unbundledValue;\n }\n return unbundle(value);\n}\n\nfunction validateObject(options) {\n const key = options.key;\n const object = options.value;\n const elementSpecs = options.valueSpec || {};\n const elementValidators = options.objectElementValidators || {};\n const style = options.style;\n const styleSpec = options.styleSpec;\n const validateSpec = options.validateSpec;\n let errors = [];\n const type = getType(object);\n if (type !== 'object') {\n return [new ValidationError(key, object, `object expected, ${type} found`)];\n }\n for (const objectKey in object) {\n const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint'\n const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*'];\n let validateElement;\n if (elementValidators[elementSpecKey]) {\n validateElement = elementValidators[elementSpecKey];\n }\n else if (elementSpecs[elementSpecKey]) {\n validateElement = validateSpec;\n }\n else if (elementValidators['*']) {\n validateElement = elementValidators['*'];\n }\n else if (elementSpecs['*']) {\n validateElement = validateSpec;\n }\n else {\n errors.push(new ValidationError(key, object[objectKey], `unknown property \"${objectKey}\"`));\n continue;\n }\n errors = errors.concat(validateElement({\n key: (key ? `${key}.` : key) + objectKey,\n value: object[objectKey],\n valueSpec: elementSpec,\n style,\n styleSpec,\n object,\n objectKey,\n validateSpec,\n }, object));\n }\n for (const elementSpecKey in elementSpecs) {\n // Don't check `required` when there's a custom validator for that property.\n if (elementValidators[elementSpecKey]) {\n continue;\n }\n if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) {\n errors.push(new ValidationError(key, object, `missing required property \"${elementSpecKey}\"`));\n }\n }\n return errors;\n}\n\nfunction validateArray(options) {\n const array = options.value;\n const arraySpec = options.valueSpec;\n const validateSpec = options.validateSpec;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const key = options.key;\n const validateArrayElement = options.arrayElementValidator || validateSpec;\n if (getType(array) !== 'array') {\n return [new ValidationError(key, array, `array expected, ${getType(array)} found`)];\n }\n if (arraySpec.length && array.length !== arraySpec.length) {\n return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)];\n }\n if (arraySpec['min-length'] && array.length < arraySpec['min-length']) {\n return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)];\n }\n let arrayElementSpec = {\n 'type': arraySpec.value,\n 'values': arraySpec.values\n };\n if (styleSpec.$version < 7) {\n arrayElementSpec['function'] = arraySpec.function;\n }\n if (getType(arraySpec.value) === 'object') {\n arrayElementSpec = arraySpec.value;\n }\n let errors = [];\n for (let i = 0; i < array.length; i++) {\n errors = errors.concat(validateArrayElement({\n array,\n arrayIndex: i,\n value: array[i],\n valueSpec: arrayElementSpec,\n validateSpec: options.validateSpec,\n style,\n styleSpec,\n key: `${key}[${i}]`\n }));\n }\n return errors;\n}\n\nfunction validateNumber(options) {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n let type = getType(value);\n // eslint-disable-next-line no-self-compare\n if (type === 'number' && value !== value) {\n type = 'NaN';\n }\n if (type !== 'number') {\n return [new ValidationError(key, value, `number expected, ${type} found`)];\n }\n if ('minimum' in valueSpec && value < valueSpec.minimum) {\n return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)];\n }\n if ('maximum' in valueSpec && value > valueSpec.maximum) {\n return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)];\n }\n return [];\n}\n\nfunction validateFunction(options) {\n const functionValueSpec = options.valueSpec;\n const functionType = unbundle(options.value.type);\n let stopKeyType;\n let stopDomainValues = {};\n let previousStopDomainValue;\n let previousStopDomainZoom;\n const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined;\n const isPropertyFunction = !isZoomFunction;\n const isZoomAndPropertyFunction = getType(options.value.stops) === 'array' &&\n getType(options.value.stops[0]) === 'array' &&\n getType(options.value.stops[0][0]) === 'object';\n const errors = validateObject({\n key: options.key,\n value: options.value,\n valueSpec: options.styleSpec.function,\n validateSpec: options.validateSpec,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n stops: validateFunctionStops,\n default: validateFunctionDefault\n }\n });\n if (functionType === 'identity' && isZoomFunction) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"property\"'));\n }\n if (functionType !== 'identity' && !options.value.stops) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"stops\"'));\n }\n if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported'));\n }\n if (options.styleSpec.$version >= 8) {\n if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'property functions not supported'));\n }\n else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported'));\n }\n }\n if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) {\n errors.push(new ValidationError(options.key, options.value, '\"property\" property is required'));\n }\n return errors;\n function validateFunctionStops(options) {\n if (functionType === 'identity') {\n return [new ValidationError(options.key, options.value, 'identity function may not have a \"stops\" property')];\n }\n let errors = [];\n const value = options.value;\n errors = errors.concat(validateArray({\n key: options.key,\n value,\n valueSpec: options.valueSpec,\n validateSpec: options.validateSpec,\n style: options.style,\n styleSpec: options.styleSpec,\n arrayElementValidator: validateFunctionStop\n }));\n if (getType(value) === 'array' && value.length === 0) {\n errors.push(new ValidationError(options.key, value, 'array must have at least one stop'));\n }\n return errors;\n }\n function validateFunctionStop(options) {\n let errors = [];\n const value = options.value;\n const key = options.key;\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n if (value.length !== 2) {\n return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)];\n }\n if (isZoomAndPropertyFunction) {\n if (getType(value[0]) !== 'object') {\n return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)];\n }\n if (value[0].zoom === undefined) {\n return [new ValidationError(key, value, 'object stop key must have zoom')];\n }\n if (value[0].value === undefined) {\n return [new ValidationError(key, value, 'object stop key must have value')];\n }\n if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) {\n return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')];\n }\n if (unbundle(value[0].zoom) !== previousStopDomainZoom) {\n previousStopDomainZoom = unbundle(value[0].zoom);\n previousStopDomainValue = undefined;\n stopDomainValues = {};\n }\n errors = errors.concat(validateObject({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: { zoom: {} },\n validateSpec: options.validateSpec,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: { zoom: validateNumber, value: validateStopDomainValue }\n }));\n }\n else {\n errors = errors.concat(validateStopDomainValue({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: {},\n validateSpec: options.validateSpec,\n style: options.style,\n styleSpec: options.styleSpec\n }, value));\n }\n if (isExpression(deepUnbundle(value[1]))) {\n return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]);\n }\n return errors.concat(options.validateSpec({\n key: `${key}[1]`,\n value: value[1],\n valueSpec: functionValueSpec,\n validateSpec: options.validateSpec,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n }\n function validateStopDomainValue(options, stop) {\n const type = getType(options.value);\n const value = unbundle(options.value);\n const reportValue = options.value !== null ? options.value : stop;\n if (!stopKeyType) {\n stopKeyType = type;\n }\n else if (type !== stopKeyType) {\n return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)];\n }\n if (type !== 'number' && type !== 'string' && type !== 'boolean') {\n return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')];\n }\n if (type !== 'number' && functionType !== 'categorical') {\n let message = `number expected, ${type} found`;\n if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) {\n message += '\\nIf you intended to use a categorical function, specify `\"type\": \"categorical\"`.';\n }\n return [new ValidationError(options.key, reportValue, message)];\n }\n if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) {\n return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)];\n }\n if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')];\n }\n else {\n previousStopDomainValue = value;\n }\n if (functionType === 'categorical' && value in stopDomainValues) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')];\n }\n else {\n stopDomainValues[value] = true;\n }\n return [];\n }\n function validateFunctionDefault(options) {\n return options.validateSpec({\n key: options.key,\n value: options.value,\n valueSpec: functionValueSpec,\n validateSpec: options.validateSpec,\n style: options.style,\n styleSpec: options.styleSpec\n });\n }\n}\n\nfunction validateExpression(options) {\n const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec);\n if (expression.result === 'error') {\n return expression.value.map((error) => {\n return new ValidationError(`${options.key}${error.key}`, options.value, error.message);\n });\n }\n const expressionObj = expression.value.expression || expression.value._styleExpression.expression;\n if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') &&\n !expressionObj.outputDefined()) {\n return [new ValidationError(options.key, options.value, `Invalid data expression for \"${options.propertyKey}\". Output values must be contained as literals within the expression.`)];\n }\n if (options.expressionContext === 'property' && options.propertyType === 'layout' &&\n (!isStateConstant(expressionObj))) {\n return [new ValidationError(options.key, options.value, '\"feature-state\" data expressions are not supported with layout properties.')];\n }\n if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) {\n return [new ValidationError(options.key, options.value, '\"feature-state\" data expressions are not supported with filters.')];\n }\n if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) {\n if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) {\n return [new ValidationError(options.key, options.value, '\"zoom\" and \"feature-state\" expressions are not supported with cluster properties.')];\n }\n if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) {\n return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')];\n }\n }\n return [];\n}\n\nfunction validateBoolean(options) {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n if (type !== 'boolean') {\n return [new ValidationError(key, value, `boolean expected, ${type} found`)];\n }\n return [];\n}\n\nfunction validateColor(options) {\n const key = options.key;\n const value = options.value;\n const type = getType(value);\n if (type !== 'string') {\n return [new ValidationError(key, value, `color expected, ${type} found`)];\n }\n if (!Color.parse(String(value))) { // cast String object to string primitive\n return [new ValidationError(key, value, `color expected, \"${value}\" found`)];\n }\n return [];\n}\n\nfunction validateEnum(options) {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n const errors = [];\n if (Array.isArray(valueSpec.values)) { // <=v7\n if (valueSpec.values.indexOf(unbundle(value)) === -1) {\n errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`));\n }\n }\n else { // >=v8\n if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) {\n errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`));\n }\n }\n return errors;\n}\n\nfunction validateFilter(options) {\n if (isExpressionFilter(deepUnbundle(options.value))) {\n return validateExpression(extendBy({}, options, {\n expressionContext: 'filter',\n valueSpec: { value: 'boolean' }\n }));\n }\n else {\n return validateNonExpressionFilter(options);\n }\n}\nfunction validateNonExpressionFilter(options) {\n const value = options.value;\n const key = options.key;\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n const styleSpec = options.styleSpec;\n let type;\n let errors = [];\n if (value.length < 1) {\n return [new ValidationError(key, value, 'filter array must have at least 1 element')];\n }\n errors = errors.concat(validateEnum({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: styleSpec.filter_operator,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n switch (unbundle(value[0])) {\n case '<':\n case '<=':\n case '>':\n case '>=':\n if (value.length >= 2 && unbundle(value[1]) === '$type') {\n errors.push(new ValidationError(key, value, `\"$type\" cannot be use with operator \"${value[0]}\"`));\n }\n /* falls through */\n case '==':\n case '!=':\n if (value.length !== 3) {\n errors.push(new ValidationError(key, value, `filter array for operator \"${value[0]}\" must have 3 elements`));\n }\n /* falls through */\n case 'in':\n case '!in':\n if (value.length >= 2) {\n type = getType(value[1]);\n if (type !== 'string') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n }\n }\n for (let i = 2; i < value.length; i++) {\n type = getType(value[i]);\n if (unbundle(value[1]) === '$type') {\n errors = errors.concat(validateEnum({\n key: `${key}[${i}]`,\n value: value[i],\n valueSpec: styleSpec.geometry_type,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n }\n else if (type !== 'string' && type !== 'number' && type !== 'boolean') {\n errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`));\n }\n }\n break;\n case 'any':\n case 'all':\n case 'none':\n for (let i = 1; i < value.length; i++) {\n errors = errors.concat(validateNonExpressionFilter({\n key: `${key}[${i}]`,\n value: value[i],\n style: options.style,\n styleSpec: options.styleSpec\n }));\n }\n break;\n case 'has':\n case '!has':\n type = getType(value[1]);\n if (value.length !== 2) {\n errors.push(new ValidationError(key, value, `filter array for \"${value[0]}\" operator must have 2 elements`));\n }\n else if (type !== 'string') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n }\n break;\n }\n return errors;\n}\n\nfunction validateProperty(options, propertyType) {\n const key = options.key;\n const validateSpec = options.validateSpec;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const value = options.value;\n const propertyKey = options.objectKey;\n const layerSpec = styleSpec[`${propertyType}_${options.layerType}`];\n if (!layerSpec)\n return [];\n const transitionMatch = propertyKey.match(/^(.*)-transition$/);\n if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) {\n return validateSpec({\n key,\n value,\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n });\n }\n const valueSpec = options.valueSpec || layerSpec[propertyKey];\n if (!valueSpec) {\n return [new ValidationError(key, value, `unknown property \"${propertyKey}\"`)];\n }\n let tokenMatch;\n if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) {\n return [new ValidationError(key, value, `\"${propertyKey}\" does not support interpolation syntax\\n` +\n `Use an identity property function instead: \\`{ \"type\": \"identity\", \"property\": ${JSON.stringify(tokenMatch[1])} }\\`.`)];\n }\n const errors = [];\n if (options.layerType === 'symbol') {\n if (propertyKey === 'text-field' && style && !style.glyphs) {\n errors.push(new ValidationError(key, value, 'use of \"text-field\" requires a style \"glyphs\" property'));\n }\n if (propertyKey === 'text-font' && isFunction$1(deepUnbundle(value)) && unbundle(value.type) === 'identity') {\n errors.push(new ValidationError(key, value, '\"text-font\" does not support identity functions'));\n }\n }\n return errors.concat(validateSpec({\n key: options.key,\n value,\n valueSpec,\n style,\n styleSpec,\n expressionContext: 'property',\n propertyType,\n propertyKey\n }));\n}\n\nfunction validatePaintProperty(options) {\n return validateProperty(options, 'paint');\n}\n\nfunction validateLayoutProperty(options) {\n return validateProperty(options, 'layout');\n}\n\nfunction validateLayer(options) {\n let errors = [];\n const layer = options.value;\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n if (!layer.type && !layer.ref) {\n errors.push(new ValidationError(key, layer, 'either \"type\" or \"ref\" is required'));\n }\n let type = unbundle(layer.type);\n const ref = unbundle(layer.ref);\n if (layer.id) {\n const layerId = unbundle(layer.id);\n for (let i = 0; i < options.arrayIndex; i++) {\n const otherLayer = style.layers[i];\n if (unbundle(otherLayer.id) === layerId) {\n errors.push(new ValidationError(key, layer.id, `duplicate layer id \"${layer.id}\", previously used at line ${otherLayer.id.__line__}`));\n }\n }\n }\n if ('ref' in layer) {\n ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => {\n if (p in layer) {\n errors.push(new ValidationError(key, layer[p], `\"${p}\" is prohibited for ref layers`));\n }\n });\n let parent;\n style.layers.forEach((layer) => {\n if (unbundle(layer.id) === ref)\n parent = layer;\n });\n if (!parent) {\n errors.push(new ValidationError(key, layer.ref, `ref layer \"${ref}\" not found`));\n }\n else if (parent.ref) {\n errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer'));\n }\n else {\n type = unbundle(parent.type);\n }\n }\n else if (type !== 'background') {\n if (!layer.source) {\n errors.push(new ValidationError(key, layer, 'missing required property \"source\"'));\n }\n else {\n const source = style.sources && style.sources[layer.source];\n const sourceType = source && unbundle(source.type);\n if (!source) {\n errors.push(new ValidationError(key, layer.source, `source \"${layer.source}\" not found`));\n }\n else if (sourceType === 'vector' && type === 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster source`));\n }\n else if (sourceType !== 'raster-dem' && type === 'hillshade') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster-dem source`));\n }\n else if (sourceType === 'raster' && type !== 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a vector source`));\n }\n else if (sourceType === 'vector' && !layer['source-layer']) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" must specify a \"source-layer\"`));\n }\n else if (sourceType === 'raster-dem' && type !== 'hillshade') {\n errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \\'hillshade\\'.'));\n }\n else if (type === 'line' && layer.paint && layer.paint['line-gradient'] &&\n (sourceType !== 'geojson' || !source.lineMetrics)) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" specifies a line-gradient, which requires a GeoJSON source with \\`lineMetrics\\` enabled.`));\n }\n }\n }\n errors = errors.concat(validateObject({\n key,\n value: layer,\n valueSpec: styleSpec.layer,\n style: options.style,\n styleSpec: options.styleSpec,\n validateSpec: options.validateSpec,\n objectElementValidators: {\n '*'() {\n return [];\n },\n // We don't want to enforce the spec's `\"requires\": true` for backward compatibility with refs;\n // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772.\n type() {\n return options.validateSpec({\n key: `${key}.type`,\n value: layer.type,\n valueSpec: styleSpec.layer.type,\n style: options.style,\n styleSpec: options.styleSpec,\n validateSpec: options.validateSpec,\n object: layer,\n objectKey: 'type'\n });\n },\n filter: validateFilter,\n layout(options) {\n return validateObject({\n layer,\n key: options.key,\n value: options.value,\n style: options.style,\n styleSpec: options.styleSpec,\n validateSpec: options.validateSpec,\n objectElementValidators: {\n '*'(options) {\n return validateLayoutProperty(extendBy({ layerType: type }, options));\n }\n }\n });\n },\n paint(options) {\n return validateObject({\n layer,\n key: options.key,\n value: options.value,\n style: options.style,\n styleSpec: options.styleSpec,\n validateSpec: options.validateSpec,\n objectElementValidators: {\n '*'(options) {\n return validatePaintProperty(extendBy({ layerType: type }, options));\n }\n }\n });\n }\n }\n }));\n return errors;\n}\n\nfunction validateString(options) {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n if (type !== 'string') {\n return [new ValidationError(key, value, `string expected, ${type} found`)];\n }\n return [];\n}\n\nfunction validateRasterDEMSource(options) {\n var _a;\n const sourceName = (_a = options.sourceName) !== null && _a !== void 0 ? _a : '';\n const rasterDEM = options.value;\n const styleSpec = options.styleSpec;\n const rasterDEMSpec = styleSpec.source_raster_dem;\n const style = options.style;\n let errors = [];\n const rootType = getType(rasterDEM);\n if (rasterDEM === undefined) {\n return errors;\n }\n else if (rootType !== 'object') {\n errors.push(new ValidationError('source_raster_dem', rasterDEM, `object expected, ${rootType} found`));\n return errors;\n }\n const encoding = unbundle(rasterDEM.encoding);\n const isCustomEncoding = encoding === 'custom';\n const customEncodingKeys = ['redFactor', 'greenFactor', 'blueFactor', 'baseShift'];\n const encodingName = options.value.encoding ? `\"${options.value.encoding}\"` : 'Default';\n for (const key in rasterDEM) {\n if (!isCustomEncoding && customEncodingKeys.includes(key)) {\n errors.push(new ValidationError(key, rasterDEM[key], `In \"${sourceName}\": \"${key}\" is only valid when \"encoding\" is set to \"custom\". ${encodingName} encoding found`));\n }\n else if (rasterDEMSpec[key]) {\n errors = errors.concat(options.validateSpec({\n key,\n value: rasterDEM[key],\n valueSpec: rasterDEMSpec[key],\n validateSpec: options.validateSpec,\n style,\n styleSpec\n }));\n }\n else {\n errors.push(new ValidationError(key, rasterDEM[key], `unknown property \"${key}\"`));\n }\n }\n return errors;\n}\n\nconst objectElementValidators = {\n promoteId: validatePromoteId\n};\nfunction validateSource(options) {\n const value = options.value;\n const key = options.key;\n const styleSpec = options.styleSpec;\n const style = options.style;\n const validateSpec = options.validateSpec;\n if (!value.type) {\n return [new ValidationError(key, value, '\"type\" is required')];\n }\n const type = unbundle(value.type);\n let errors;\n switch (type) {\n case 'vector':\n case 'raster':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec[`source_${type.replace('-', '_')}`],\n style: options.style,\n styleSpec,\n objectElementValidators,\n validateSpec,\n });\n return errors;\n case 'raster-dem':\n errors = validateRasterDEMSource({\n sourceName: key,\n value,\n style: options.style,\n styleSpec,\n validateSpec,\n });\n return errors;\n case 'geojson':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec.source_geojson,\n style,\n styleSpec,\n validateSpec,\n objectElementValidators\n });\n if (value.cluster) {\n for (const prop in value.clusterProperties) {\n const [operator, mapExpr] = value.clusterProperties[prop];\n const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator;\n errors.push(...validateExpression({\n key: `${key}.${prop}.map`,\n value: mapExpr,\n validateSpec,\n expressionContext: 'cluster-map'\n }));\n errors.push(...validateExpression({\n key: `${key}.${prop}.reduce`,\n value: reduceExpr,\n validateSpec,\n expressionContext: 'cluster-reduce'\n }));\n }\n }\n return errors;\n case 'video':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_video,\n style,\n validateSpec,\n styleSpec\n });\n case 'image':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_image,\n style,\n validateSpec,\n styleSpec\n });\n case 'canvas':\n return [new ValidationError(key, null, 'Please use runtime APIs to add canvas sources, rather than including them in stylesheets.', 'source.canvas')];\n default:\n return validateEnum({\n key: `${key}.type`,\n value: value.type,\n valueSpec: { values: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image'] },\n style,\n validateSpec,\n styleSpec\n });\n }\n}\nfunction validatePromoteId({ key, value }) {\n if (getType(value) === 'string') {\n return validateString({ key, value });\n }\n else {\n const errors = [];\n for (const prop in value) {\n errors.push(...validateString({ key: `${key}.${prop}`, value: value[prop] }));\n }\n return errors;\n }\n}\n\nfunction validateLight(options) {\n const light = options.value;\n const styleSpec = options.styleSpec;\n const lightSpec = styleSpec.light;\n const style = options.style;\n let errors = [];\n const rootType = getType(light);\n if (light === undefined) {\n return errors;\n }\n else if (rootType !== 'object') {\n errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]);\n return errors;\n }\n for (const key in light) {\n const transitionMatch = key.match(/^(.*)-transition$/);\n if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) {\n errors = errors.concat(options.validateSpec({\n key,\n value: light[key],\n valueSpec: styleSpec.transition,\n validateSpec: options.validateSpec,\n style,\n styleSpec\n }));\n }\n else if (lightSpec[key]) {\n errors = errors.concat(options.validateSpec({\n key,\n value: light[key],\n valueSpec: lightSpec[key],\n validateSpec: options.validateSpec,\n style,\n styleSpec\n }));\n }\n else {\n errors = errors.concat([new ValidationError(key, light[key], `unknown property \"${key}\"`)]);\n }\n }\n return errors;\n}\n\nfunction validateSky(options) {\n const sky = options.value;\n const styleSpec = options.styleSpec;\n const skySpec = styleSpec.sky;\n const style = options.style;\n const rootType = getType(sky);\n if (sky === undefined) {\n return [];\n }\n else if (rootType !== 'object') {\n return [new ValidationError('sky', sky, `object expected, ${rootType} found`)];\n }\n let errors = [];\n for (const key in sky) {\n if (skySpec[key]) {\n errors = errors.concat(options.validateSpec({\n key,\n value: sky[key],\n valueSpec: skySpec[key],\n style,\n styleSpec\n }));\n }\n else {\n errors = errors.concat([new ValidationError(key, sky[key], `unknown property \"${key}\"`)]);\n }\n }\n return errors;\n}\n\nfunction validateTerrain(options) {\n const terrain = options.value;\n const styleSpec = options.styleSpec;\n const terrainSpec = styleSpec.terrain;\n const style = options.style;\n let errors = [];\n const rootType = getType(terrain);\n if (terrain === undefined) {\n return errors;\n }\n else if (rootType !== 'object') {\n errors = errors.concat([new ValidationError('terrain', terrain, `object expected, ${rootType} found`)]);\n return errors;\n }\n for (const key in terrain) {\n if (terrainSpec[key]) {\n errors = errors.concat(options.validateSpec({\n key,\n value: terrain[key],\n valueSpec: terrainSpec[key],\n validateSpec: options.validateSpec,\n style,\n styleSpec\n }));\n }\n else {\n errors = errors.concat([new ValidationError(key, terrain[key], `unknown property \"${key}\"`)]);\n }\n }\n return errors;\n}\n\nfunction validateFormatted(options) {\n if (validateString(options).length === 0) {\n return [];\n }\n return validateExpression(options);\n}\n\nfunction validateImage(options) {\n if (validateString(options).length === 0) {\n return [];\n }\n return validateExpression(options);\n}\n\nfunction validatePadding(options) {\n const key = options.key;\n const value = options.value;\n const type = getType(value);\n if (type === 'array') {\n if (value.length < 1 || value.length > 4) {\n return [new ValidationError(key, value, `padding requires 1 to 4 values; ${value.length} values found`)];\n }\n const arrayElementSpec = {\n type: 'number'\n };\n let errors = [];\n for (let i = 0; i < value.length; i++) {\n errors = errors.concat(options.validateSpec({\n key: `${key}[${i}]`,\n value: value[i],\n validateSpec: options.validateSpec,\n valueSpec: arrayElementSpec\n }));\n }\n return errors;\n }\n else {\n return validateNumber({\n key,\n value,\n valueSpec: {}\n });\n }\n}\n\nfunction validateVariableAnchorOffsetCollection(options) {\n const key = options.key;\n const value = options.value;\n const type = getType(value);\n const styleSpec = options.styleSpec;\n if (type !== 'array' || value.length < 1 || value.length % 2 !== 0) {\n return [new ValidationError(key, value, 'variableAnchorOffsetCollection requires a non-empty array of even length')];\n }\n let errors = [];\n for (let i = 0; i < value.length; i += 2) {\n // Elements in even positions should be values from text-anchor enum\n errors = errors.concat(validateEnum({\n key: `${key}[${i}]`,\n value: value[i],\n valueSpec: styleSpec['layout_symbol']['text-anchor']\n }));\n // Elements in odd positions should be points (2-element numeric arrays)\n errors = errors.concat(validateArray({\n key: `${key}[${i + 1}]`,\n value: value[i + 1],\n valueSpec: {\n length: 2,\n value: 'number'\n },\n validateSpec: options.validateSpec,\n style: options.style,\n styleSpec\n }));\n }\n return errors;\n}\n\nfunction validateSprite(options) {\n let errors = [];\n const sprite = options.value;\n const key = options.key;\n if (!Array.isArray(sprite)) {\n return validateString({\n key,\n value: sprite\n });\n }\n else {\n const allSpriteIds = [];\n const allSpriteURLs = [];\n for (const i in sprite) {\n if (sprite[i].id && allSpriteIds.includes(sprite[i].id))\n errors.push(new ValidationError(key, sprite, `all the sprites' ids must be unique, but ${sprite[i].id} is duplicated`));\n allSpriteIds.push(sprite[i].id);\n if (sprite[i].url && allSpriteURLs.includes(sprite[i].url))\n errors.push(new ValidationError(key, sprite, `all the sprites' URLs must be unique, but ${sprite[i].url} is duplicated`));\n allSpriteURLs.push(sprite[i].url);\n const pairSpec = {\n id: {\n type: 'string',\n required: true,\n },\n url: {\n type: 'string',\n required: true,\n }\n };\n errors = errors.concat(validateObject({\n key: `${key}[${i}]`,\n value: sprite[i],\n valueSpec: pairSpec,\n validateSpec: options.validateSpec,\n }));\n }\n return errors;\n }\n}\n\nfunction validateProjection(options) {\n const projection = options.value;\n const styleSpec = options.styleSpec;\n const projectionSpec = styleSpec.projection;\n const style = options.style;\n const rootType = getType(projection);\n if (projection === undefined) {\n return [];\n }\n else if (rootType !== 'object') {\n return [new ValidationError('projection', projection, `object expected, ${rootType} found`)];\n }\n let errors = [];\n for (const key in projection) {\n if (projectionSpec[key]) {\n errors = errors.concat(options.validateSpec({\n key,\n value: projection[key],\n valueSpec: projectionSpec[key],\n style,\n styleSpec\n }));\n }\n else {\n errors = errors.concat([new ValidationError(key, projection[key], `unknown property \"${key}\"`)]);\n }\n }\n return errors;\n}\n\nconst VALIDATORS = {\n '*'() {\n return [];\n },\n 'array': validateArray,\n 'boolean': validateBoolean,\n 'number': validateNumber,\n 'color': validateColor,\n 'constants': validateConstants,\n 'enum': validateEnum,\n 'filter': validateFilter,\n 'function': validateFunction,\n 'layer': validateLayer,\n 'object': validateObject,\n 'source': validateSource,\n 'light': validateLight,\n 'sky': validateSky,\n 'terrain': validateTerrain,\n 'projection': validateProjection,\n 'string': validateString,\n 'formatted': validateFormatted,\n 'resolvedImage': validateImage,\n 'padding': validatePadding,\n 'variableAnchorOffsetCollection': validateVariableAnchorOffsetCollection,\n 'sprite': validateSprite,\n};\n/**\n * Main recursive validation function used internally.\n * You should use `validateStyleMin` in the browser or `validateStyle` in node env.\n * @param options - the options object\n * @param options.key - string representing location of validation in style tree. Used only\n * for more informative error reporting.\n * @param options.value - current value from style being evaluated. May be anything from a\n * high level object that needs to be descended into deeper or a simple\n * scalar value.\n * @param options.valueSpec - current spec being evaluated. Tracks value.\n * @param options.styleSpec - current full spec being evaluated.\n * @param options.validateSpec - the validate function itself\n * @param options.style - the style object\n * @param options.objectElementValidators - optional object of functions that will be called\n * @returns an array of errors, or an empty array if no errors are found.\n */\nfunction validate(options) {\n const value = options.value;\n const valueSpec = options.valueSpec;\n const styleSpec = options.styleSpec;\n options.validateSpec = validate;\n if (valueSpec.expression && isFunction$1(unbundle(value))) {\n return validateFunction(options);\n }\n else if (valueSpec.expression && isExpression(deepUnbundle(value))) {\n return validateExpression(options);\n }\n else if (valueSpec.type && VALIDATORS[valueSpec.type]) {\n return VALIDATORS[valueSpec.type](options);\n }\n else {\n const valid = validateObject(extendBy({}, options, {\n valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec\n }));\n return valid;\n }\n}\n\nfunction validateGlyphsUrl(options) {\n const value = options.value;\n const key = options.key;\n const errors = validateString(options);\n if (errors.length)\n return errors;\n if (value.indexOf('{fontstack}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{fontstack}\" token'));\n }\n if (value.indexOf('{range}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{range}\" token'));\n }\n return errors;\n}\n\n/**\n * Validate a MapLibre style against the style specification.\n * Use this when running in the browser.\n *\n * @param style - The style to be validated.\n * @param styleSpec - The style specification to validate against.\n * If omitted, the latest style spec is used.\n * @returns an array of errors, or an empty array if no errors are found.\n * @example\n * const validate = require('@maplibre/maplibre-gl-style-spec/').validateStyleMin;\n * const errors = validate(style);\n */\nfunction validateStyleMin(style, styleSpec = v8Spec) {\n let errors = [];\n errors = errors.concat(validate({\n key: '',\n value: style,\n valueSpec: styleSpec.$root,\n styleSpec,\n style,\n validateSpec: validate,\n objectElementValidators: {\n glyphs: validateGlyphsUrl,\n '*'() {\n return [];\n }\n }\n }));\n if (style['constants']) {\n errors = errors.concat(validateConstants({\n key: 'constants',\n value: style['constants'],\n style,\n styleSpec,\n validateSpec: validate,\n }));\n }\n return sortErrors(errors);\n}\nvalidateStyleMin.source = wrapCleanErrors(injectValidateSpec(validateSource));\nvalidateStyleMin.sprite = wrapCleanErrors(injectValidateSpec(validateSprite));\nvalidateStyleMin.glyphs = wrapCleanErrors(injectValidateSpec(validateGlyphsUrl));\nvalidateStyleMin.light = wrapCleanErrors(injectValidateSpec(validateLight));\nvalidateStyleMin.sky = wrapCleanErrors(injectValidateSpec(validateSky));\nvalidateStyleMin.terrain = wrapCleanErrors(injectValidateSpec(validateTerrain));\nvalidateStyleMin.layer = wrapCleanErrors(injectValidateSpec(validateLayer));\nvalidateStyleMin.filter = wrapCleanErrors(injectValidateSpec(validateFilter));\nvalidateStyleMin.paintProperty = wrapCleanErrors(injectValidateSpec(validatePaintProperty));\nvalidateStyleMin.layoutProperty = wrapCleanErrors(injectValidateSpec(validateLayoutProperty));\nfunction injectValidateSpec(validator) {\n return function (options) {\n return validator({\n ...options,\n validateSpec: validate,\n });\n };\n}\nfunction sortErrors(errors) {\n return [].concat(errors).sort((a, b) => {\n return a.line - b.line;\n });\n}\nfunction wrapCleanErrors(inner) {\n return function (...args) {\n return sortErrors(inner.apply(this, args));\n };\n}\n\n// Note: This regex matches even invalid JSON strings, but since we’re\n// working on the output of `JSON.stringify` we know that only valid strings\n// are present (unless the user supplied a weird `options.indent` but in\n// that case we don’t care since the output would be invalid anyway).\nconst stringOrChar = /(\"(?:[^\\\\\"]|\\\\.)*\")|[:,]/g;\n\nfunction stringify(passedObj, options = {}) {\n const indent = JSON.stringify(\n [1],\n undefined,\n options.indent === undefined ? 2 : options.indent\n ).slice(2, -3);\n\n const maxLength =\n indent === \"\"\n ? Infinity\n : options.maxLength === undefined\n ? 80\n : options.maxLength;\n\n let { replacer } = options;\n\n return (function _stringify(obj, currentIndent, reserved) {\n if (obj && typeof obj.toJSON === \"function\") {\n obj = obj.toJSON();\n }\n\n const string = JSON.stringify(obj, replacer);\n\n if (string === undefined) {\n return string;\n }\n\n const length = maxLength - currentIndent.length - reserved;\n\n if (string.length <= length) {\n const prettified = string.replace(\n stringOrChar,\n (match, stringLiteral) => {\n return stringLiteral || `${match} `;\n }\n );\n if (prettified.length <= length) {\n return prettified;\n }\n }\n\n if (replacer != null) {\n obj = JSON.parse(string);\n replacer = undefined;\n }\n\n if (typeof obj === \"object\" && obj !== null) {\n const nextIndent = currentIndent + indent;\n const items = [];\n let index = 0;\n let start;\n let end;\n\n if (Array.isArray(obj)) {\n start = \"[\";\n end = \"]\";\n const { length } = obj;\n for (; index < length; index++) {\n items.push(\n _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) ||\n \"null\"\n );\n }\n } else {\n start = \"{\";\n end = \"}\";\n const keys = Object.keys(obj);\n const { length } = keys;\n for (; index < length; index++) {\n const key = keys[index];\n const keyPart = `${JSON.stringify(key)}: `;\n const value = _stringify(\n obj[key],\n nextIndent,\n keyPart.length + (index === length - 1 ? 0 : 1)\n );\n if (value !== undefined) {\n items.push(keyPart + value);\n }\n }\n }\n\n if (items.length > 0) {\n return [start, indent + items.join(`,\\n${nextIndent}`), end].join(\n `\\n${currentIndent}`\n );\n }\n }\n\n return string;\n })(passedObj, \"\", 0);\n}\n\nfunction sortKeysBy(obj, reference) {\n const result = {};\n for (const key in reference) {\n if (obj[key] !== undefined) {\n result[key] = obj[key];\n }\n }\n for (const key in obj) {\n if (result[key] === undefined) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n/**\n * Format a MapLibre Style. Returns a stringified style with its keys\n * sorted in the same order as the reference style.\n *\n * The optional `space` argument is passed to\n * [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)\n * to generate formatted output.\n *\n * If `space` is unspecified, a default of `2` spaces will be used.\n *\n * @private\n * @param {Object} style a MapLibre Style\n * @param {number} [space] space argument to pass to `JSON.stringify`\n * @returns {string} stringified formatted JSON\n * @example\n * var fs = require('fs');\n * var format = require('maplibre-gl-style-spec').format;\n * var style = fs.readFileSync('./source.json', 'utf8');\n * fs.writeFileSync('./dest.json', format(style));\n * fs.writeFileSync('./dest.min.json', format(style, 0));\n */\nfunction format(style, space = 2) {\n style = sortKeysBy(style, v8Spec.$root);\n if (style.layers) {\n style.layers = style.layers.map((layer) => sortKeysBy(layer, v8Spec.layer));\n }\n return stringify(style, { indent: space });\n}\n\nfunction eachLayout(layer, callback) {\n for (const k in layer) {\n if (k.indexOf('layout') === 0) {\n callback(layer[k], k);\n }\n }\n}\nfunction eachPaint(layer, callback) {\n for (const k in layer) {\n if (k.indexOf('paint') === 0) {\n callback(layer[k], k);\n }\n }\n}\nfunction resolveConstant(style, value) {\n if (typeof value === 'string' && value[0] === '@') {\n return resolveConstant(style, style.constants[value]);\n }\n else {\n return value;\n }\n}\nfunction isFunction(value) {\n return Array.isArray(value.stops);\n}\nfunction renameProperty(obj, from, to) {\n obj[to] = obj[from];\n delete obj[from];\n}\nfunction migrateV8(style) {\n style.version = 8;\n // Rename properties, reverse coordinates in source and layers\n eachSource(style, (source) => {\n if (source.type === 'video' && source['url'] !== undefined) {\n renameProperty(source, 'url', 'urls');\n }\n if (source.type === 'video') {\n source.coordinates.forEach((coord) => {\n return coord.reverse();\n });\n }\n });\n eachLayer(style, (layer) => {\n eachLayout(layer, (layout) => {\n if (layout['symbol-min-distance'] !== undefined) {\n renameProperty(layout, 'symbol-min-distance', 'symbol-spacing');\n }\n });\n eachPaint(layer, (paint) => {\n if (paint['background-image'] !== undefined) {\n renameProperty(paint, 'background-image', 'background-pattern');\n }\n if (paint['line-image'] !== undefined) {\n renameProperty(paint, 'line-image', 'line-pattern');\n }\n if (paint['fill-image'] !== undefined) {\n renameProperty(paint, 'fill-image', 'fill-pattern');\n }\n });\n });\n // Inline Constants\n eachProperty(style, { paint: true, layout: true }, (property) => {\n const value = resolveConstant(style, property.value);\n if (isFunction(value)) {\n value.stops.forEach((stop) => {\n stop[1] = resolveConstant(style, stop[1]);\n });\n }\n property.set(value);\n });\n delete style['constants'];\n eachLayer(style, (layer) => {\n // get rid of text-max-size, icon-max-size\n // turn text-size, icon-size into layout properties\n // https://github.com/mapbox/mapbox-gl-style-spec/issues/255\n eachLayout(layer, (layout) => {\n delete layout['text-max-size'];\n delete layout['icon-max-size'];\n });\n eachPaint(layer, (paint) => {\n if (paint['text-size']) {\n if (!layer.layout)\n layer.layout = {};\n layer.layout['text-size'] = paint['text-size'];\n delete paint['text-size'];\n }\n if (paint['icon-size']) {\n if (!layer.layout)\n layer.layout = {};\n layer.layout['icon-size'] = paint['icon-size'];\n delete paint['icon-size'];\n }\n });\n });\n function migrateFontStack(font) {\n function splitAndTrim(string) {\n return string.split(',').map((s) => {\n return s.trim();\n });\n }\n if (Array.isArray(font)) {\n // Assume it's a previously migrated font-array.\n return font;\n }\n else if (typeof font === 'string') {\n return splitAndTrim(font);\n }\n else if (typeof font === 'object') {\n font.stops.forEach((stop) => {\n stop[1] = splitAndTrim(stop[1]);\n });\n return font;\n }\n else {\n throw new Error('unexpected font value');\n }\n }\n eachLayer(style, (layer) => {\n eachLayout(layer, (layout) => {\n if (layout['text-font']) {\n layout['text-font'] = migrateFontStack(layout['text-font']);\n }\n });\n });\n // Reverse order of symbol layers. This is an imperfect migration.\n //\n // The order of a symbol layer in the layers list affects two things:\n // - how it is drawn relative to other layers (like oneway arrows below bridges)\n // - the placement priority compared to other layers\n //\n // It's impossible to reverse the placement priority without breaking the draw order\n // in some cases. This migration only reverses the order of symbol layers that\n // are above all other types of layers.\n //\n // Symbol layers that are at the top of the map preserve their priority.\n // Symbol layers that are below another type (line, fill) of layer preserve their draw order.\n let firstSymbolLayer = 0;\n for (let i = style.layers.length - 1; i >= 0; i--) {\n const layer = style.layers[i];\n if (layer.type !== 'symbol') {\n firstSymbolLayer = i + 1;\n break;\n }\n }\n const symbolLayers = style.layers.splice(firstSymbolLayer);\n symbolLayers.reverse();\n style.layers = style.layers.concat(symbolLayers);\n return style;\n}\n\n/**\n * Migrate the given style object in place to use expressions. Specifically,\n * this will convert (a) \"stop\" functions, and (b) legacy filters to their\n * expression equivalents.\n * @param style The style object to migrate.\n * @returns The migrated style object.\n */\nfunction expressions(style) {\n const converted = [];\n eachLayer(style, (layer) => {\n if (layer.filter) {\n layer.filter = convertFilter(layer.filter);\n }\n });\n eachProperty(style, { paint: true, layout: true }, ({ path, value, reference, set }) => {\n if (isExpression(value))\n return;\n if (typeof value === 'object' && !Array.isArray(value)) {\n set(convertFunction(value, reference));\n converted.push(path.join('.'));\n }\n else if (reference.tokens && typeof value === 'string') {\n set(convertTokenString(value));\n }\n });\n return style;\n}\n\n/**\n * Migrate color style values to supported format.\n *\n * @param colorToMigrate Color value to migrate, could be a string or an expression.\n * @returns Color style value in supported format.\n */\nfunction migrateColors(colorToMigrate) {\n return JSON.parse(migrateHslColors(JSON.stringify(colorToMigrate)));\n}\n/**\n * Created to migrate from colors supported by the former CSS color parsing\n * library `csscolorparser` but not compliant with the CSS Color specification,\n * like `hsl(900, 0.15, 90%)`.\n *\n * @param colorToMigrate Serialized color style value.\n * @returns A serialized color style value in which all non-standard hsl color values\n * have been converted to a format that complies with the CSS Color specification.\n *\n * @example\n * migrateHslColors('\"hsl(900, 0.15, 90%)\"'); // returns '\"hsl(900, 15%, 90%)\"'\n * migrateHslColors('\"hsla(900, .15, .9)\"'); // returns '\"hsl(900, 15%, 90%)\"'\n * migrateHslColors('\"hsl(900, 15%, 90%)\"'); // returns '\"hsl(900, 15%, 90%)\"' - no changes\n */\nfunction migrateHslColors(colorToMigrate) {\n return colorToMigrate.replace(/\"hsla?\\((.+?)\\)\"/gi, (match, hslArgs) => {\n const argsMatch = hslArgs.match(/^(.+?)\\s*,\\s*(.+?)\\s*,\\s*(.+?)(?:\\s*,\\s*(.+))?$/i);\n if (argsMatch) {\n let [h, s, l, a] = argsMatch.slice(1);\n [s, l] = [s, l].map(v => v.endsWith('%') ? v : `${parseFloat(v) * 100}%`);\n return `\"hsl${typeof a === 'string' ? 'a' : ''}(${[h, s, l, a].filter(Boolean).join(',')})\"`;\n }\n return match;\n });\n}\n\n/**\n * Migrate a Mapbox/MapLibre GL Style to the latest version.\n *\n * @param style - a MapLibre Style\n * @returns a migrated style\n * @example\n * const fs = require('fs');\n * csont migrate = require('@maplibre/maplibre-gl-style-spec').migrate;\n * const style = fs.readFileSync('./style.json', 'utf8');\n * fs.writeFileSync('./style.json', JSON.stringify(migrate(style)));\n */\nfunction migrate(style) {\n let migrated = false;\n if (style.version === 7) {\n style = migrateV8(style);\n migrated = true;\n }\n if (style.version === 8) {\n migrated = !!expressions(style);\n migrated = true;\n }\n eachProperty(style, { paint: true, layout: true }, ({ value, reference, set }) => {\n if (reference.type === 'color') {\n set(migrateColors(value));\n }\n });\n if (!migrated) {\n throw new Error(`Cannot migrate from ${style.version}`);\n }\n return style;\n}\n\nconst v8 = v8Spec;\nconst expression = {\n StyleExpression,\n StylePropertyFunction,\n ZoomConstantExpression,\n ZoomDependentExpression,\n createExpression,\n createPropertyExpression,\n isExpression,\n isExpressionFilter,\n isZoomExpression,\n normalizePropertyExpression,\n};\nconst styleFunction = {\n convertFunction,\n createFunction,\n isFunction: isFunction$1\n};\nconst visit = { eachLayer, eachProperty, eachSource };\n\nexport { Color, ColorType, CompoundExpression, EvaluationContext, FormatExpression, Formatted, FormattedSection, FormattedType, Interpolate, Literal, NullType, Padding, ParsingError, ResolvedImage, Step, StyleExpression, StylePropertyFunction, ValidationError, VariableAnchorOffsetCollection, ZoomConstantExpression, ZoomDependentExpression, classifyRings, convertFilter, convertFunction, createExpression, createFunction, createPropertyExpression, derefLayers, diffStyles as diff, emptyStyle, expression, expressions$1 as expressions, createFilter as featureFilter, format, styleFunction as function, groupByLayout, interpolateFactory, interpolate as interpolates, isExpression, isFunction$1 as isFunction, isZoomExpression, v8Spec as latest, migrate, normalizePropertyExpression, supportsPropertyExpression, toString$1 as toString, typeOf, v8, validate, validateStyleMin, visit };\n//# sourceMappingURL=index.mjs.map\n","import {validateStyleMin} from '@maplibre/maplibre-gl-style-spec';\nimport {ErrorEvent} from '../util/evented';\n\nimport type {Evented} from '../util/evented';\n\ntype ValidationError = {\n message: string;\n line: number;\n identifier?: string;\n};\n\nexport type Validator = (a: any) => ReadonlyArray;\n\ntype ValidateStyle = {\n source: Validator;\n sprite: Validator;\n glyphs: Validator;\n layer: Validator;\n light: Validator;\n sky: Validator;\n terrain: Validator;\n filter: Validator;\n paintProperty: Validator;\n layoutProperty: Validator;\n (b: any, a?: any | null): ReadonlyArray;\n};\n\nexport const validateStyle = (validateStyleMin as unknown as ValidateStyle);\n\nexport const validateSource = validateStyle.source;\nexport const validateLight = validateStyle.light;\nexport const validateSky = validateStyle.sky;\nexport const validateTerrain = validateStyle.terrain;\nexport const validateFilter = validateStyle.filter;\nexport const validatePaintProperty = validateStyle.paintProperty;\nexport const validateLayoutProperty = validateStyle.layoutProperty;\n\nexport function emitValidationErrors(\n emitter: Evented,\n errors?: ReadonlyArray<{\n message: string;\n identifier?: string;\n }> | null\n): boolean {\n let hasErrors = false;\n if (errors && errors.length) {\n for (const error of errors) {\n emitter.fire(new ErrorEvent(new Error(error.message)));\n hasErrors = true;\n }\n }\n return hasErrors;\n}\n","/*\nThis file was copied from https://github.com/mapbox/grid-index and was\nmigrated from JavaScript to TypeScript.\n\nCopyright (c) 2016, Mapbox\n\nPermission to use, copy, modify, and/or distribute this software for any purpose\nwith or without fee is hereby granted, provided that the above copyright notice\nand this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\nOF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\nTHIS SOFTWARE.\n*/\n\nconst NUM_PARAMS = 3;\n\nexport type SerializedGrid = {\n buffer: ArrayBuffer;\n};\n\nexport class TransferableGridIndex {\n cells: number[][];\n arrayBuffer: ArrayBuffer;\n d: number;\n keys: number[];\n bboxes: number[];\n n: number;\n extent: number;\n padding: number;\n scale: any;\n uid: number;\n min: number;\n max: number;\n\n constructor(extent: number | ArrayBuffer, n?: number, padding?: number) {\n const cells = this.cells = [];\n\n if (extent instanceof ArrayBuffer) {\n this.arrayBuffer = extent;\n const array = new Int32Array(this.arrayBuffer);\n extent = array[0];\n n = array[1];\n padding = array[2];\n\n this.d = n + 2 * padding;\n for (let k = 0; k < this.d * this.d; k++) {\n const start = array[NUM_PARAMS + k];\n const end = array[NUM_PARAMS + k + 1];\n cells.push(start === end ? null : array.subarray(start, end));\n }\n const keysOffset = array[NUM_PARAMS + cells.length];\n const bboxesOffset = array[NUM_PARAMS + cells.length + 1];\n this.keys = array.subarray(keysOffset, bboxesOffset) as any as number[];\n this.bboxes = array.subarray(bboxesOffset) as any as number[];\n\n this.insert = this._insertReadonly;\n\n } else {\n this.d = n + 2 * padding;\n for (let i = 0; i < this.d * this.d; i++) {\n cells.push([]);\n }\n this.keys = [];\n this.bboxes = [];\n }\n\n this.n = n;\n this.extent = extent;\n this.padding = padding;\n this.scale = n / extent;\n this.uid = 0;\n\n const p = (padding / n) * extent;\n this.min = -p;\n this.max = extent + p;\n }\n\n insert(key: number, x1: number, y1: number, x2: number, y2: number) {\n this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++, undefined, undefined);\n this.keys.push(key);\n this.bboxes.push(x1);\n this.bboxes.push(y1);\n this.bboxes.push(x2);\n this.bboxes.push(y2);\n }\n\n _insertReadonly() {\n throw new Error('Cannot insert into a GridIndex created from an ArrayBuffer.');\n }\n\n _insertCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {\n this.cells[cellIndex].push(uid);\n }\n\n query(x1: number, y1: number, x2: number, y2: number, intersectionTest?: Function): number[] {\n const min = this.min;\n const max = this.max;\n if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) {\n // We use `Array#slice` because `this.keys` may be a `Int32Array` and\n // some browsers (Safari and IE) do not support `TypedArray#slice`\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice#Browser_compatibility\n return Array.prototype.slice.call(this.keys);\n\n } else {\n const result = [];\n const seenUids = {};\n this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest);\n return result;\n }\n }\n\n _queryCell(x1: number, y1: number, x2: number, y2:number, cellIndex:number, result, seenUids, intersectionTest: Function) {\n const cell = this.cells[cellIndex];\n if (cell !== null) {\n const keys = this.keys;\n const bboxes = this.bboxes;\n for (let u = 0; u < cell.length; u++) {\n const uid = cell[u];\n if (seenUids[uid] === undefined) {\n const offset = uid * 4;\n if (intersectionTest ?\n intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) :\n ((x1 <= bboxes[offset + 2]) &&\n (y1 <= bboxes[offset + 3]) &&\n (x2 >= bboxes[offset + 0]) &&\n (y2 >= bboxes[offset + 1]))) {\n seenUids[uid] = true;\n result.push(keys[uid]);\n } else {\n seenUids[uid] = false;\n }\n }\n }\n }\n }\n\n _forEachCell(x1: number, y1: number, x2:number, y2:number, fn: Function, arg1, arg2, intersectionTest) {\n const cx1 = this._convertToCellCoord(x1);\n const cy1 = this._convertToCellCoord(y1);\n const cx2 = this._convertToCellCoord(x2);\n const cy2 = this._convertToCellCoord(y2);\n for (let x = cx1; x <= cx2; x++) {\n for (let y = cy1; y <= cy2; y++) {\n const cellIndex = this.d * y + x;\n if (intersectionTest && !intersectionTest(\n this._convertFromCellCoord(x),\n this._convertFromCellCoord(y),\n this._convertFromCellCoord(x + 1),\n this._convertFromCellCoord(y + 1))) continue;\n if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest)) return;\n }\n }\n }\n\n _convertFromCellCoord (x) {\n return (x - this.padding) / this.scale;\n }\n\n _convertToCellCoord(x) {\n return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding));\n }\n\n toArrayBuffer(): ArrayBuffer {\n if (this.arrayBuffer) return this.arrayBuffer;\n\n const cells = this.cells;\n\n const metadataLength = NUM_PARAMS + this.cells.length + 1 + 1;\n let totalCellLength = 0;\n for (let i = 0; i < this.cells.length; i++) {\n totalCellLength += this.cells[i].length;\n }\n\n const array = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length);\n array[0] = this.extent;\n array[1] = this.n;\n array[2] = this.padding;\n\n let offset = metadataLength;\n for (let k = 0; k < cells.length; k++) {\n const cell = cells[k];\n array[NUM_PARAMS + k] = offset;\n array.set(cell, offset);\n offset += cell.length;\n }\n\n array[NUM_PARAMS + cells.length] = offset;\n array.set(this.keys, offset);\n offset += this.keys.length;\n\n array[NUM_PARAMS + cells.length + 1] = offset;\n array.set(this.bboxes, offset);\n offset += this.bboxes.length;\n\n return array.buffer;\n }\n\n public static serialize(grid: TransferableGridIndex, transferables?: Array): SerializedGrid {\n const buffer = grid.toArrayBuffer();\n if (transferables) {\n transferables.push(buffer);\n }\n return {buffer};\n }\n\n public static deserialize(serialized: SerializedGrid): TransferableGridIndex {\n return new TransferableGridIndex(serialized.buffer);\n }\n}\n","import {TransferableGridIndex} from './transferable_grid_index';\nimport {Color, CompoundExpression, expressions, ResolvedImage, StylePropertyFunction,\n StyleExpression, ZoomDependentExpression, ZoomConstantExpression} from '@maplibre/maplibre-gl-style-spec';\nimport {AJAXError} from './ajax';\nimport {isImageBitmap} from './util';\n\n/**\n * A class that is serialized to and json, that can be constructed back to the original class in the worker or in the main thread\n */\ntype SerializedObject = {\n [_: string]: S;\n};\n\n/**\n * All the possible values that can be serialized and sent to and from the worker\n */\nexport type Serialized = null | void | boolean | number | string | Boolean | Number | String | Date | RegExp | ArrayBuffer | ArrayBufferView | ImageData | ImageBitmap | Blob | Array | SerializedObject;\n\ntype Registry = {\n [_: string]: {\n klass: {\n new (...args: any): any;\n deserialize?: (input: Serialized) => unknown;\n serialize?: (input: any, transferables: Transferable[]) => SerializedObject;\n };\n omit: ReadonlyArray;\n shallow: ReadonlyArray;\n };\n};\n\n/**\n * Register options\n */\ntype RegisterOptions = {\n /**\n * List of properties to omit from serialization (e.g., cached/computed properties)\n */\n omit?: ReadonlyArray;\n /**\n * List of properties that should be serialized by a simple shallow copy, rather than by a recursive call to serialize().\n */\n shallow?: ReadonlyArray;\n};\n\nconst registry: Registry = {};\n\n/**\n * Register the given class as serializable.\n *\n * @param options - the registration options\n */\nexport function register(\n name: string,\n klass: {\n new (...args: any): T;\n },\n options: RegisterOptions = {}\n) {\n if (registry[name]) throw new Error(`${name} is already registered.`);\n ((Object.defineProperty as any))(klass, '_classRegistryKey', {\n value: name,\n writeable: false\n });\n registry[name] = {\n klass,\n omit: options.omit as ReadonlyArray || [],\n shallow: options.shallow as ReadonlyArray || []\n };\n}\n\nregister('Object', Object);\nregister('TransferableGridIndex', TransferableGridIndex);\n\nregister('Color', Color);\nregister('Error', Error);\nregister('AJAXError', AJAXError);\nregister('ResolvedImage', ResolvedImage);\n\nregister('StylePropertyFunction', StylePropertyFunction);\nregister('StyleExpression', StyleExpression, {omit: ['_evaluator']});\n\nregister('ZoomDependentExpression', ZoomDependentExpression);\nregister('ZoomConstantExpression', ZoomConstantExpression);\nregister('CompoundExpression', CompoundExpression, {omit: ['_evaluate']});\nfor (const name in expressions) {\n if ((expressions[name] as any)._classRegistryKey) continue;\n register(`Expression_${name}`, expressions[name]);\n}\n\nfunction isArrayBuffer(value: any): value is ArrayBuffer {\n return value && typeof ArrayBuffer !== 'undefined' &&\n (value instanceof ArrayBuffer || (value.constructor && value.constructor.name === 'ArrayBuffer'));\n}\n\nfunction getClassRegistryKey(input: Object|SerializedObject): string {\n const klass = (input.constructor as any);\n return (input as SerializedObject).$name || klass._classRegistryKey;\n}\n\nfunction isRegistered(input: unknown): boolean {\n if (input === null || typeof input !== 'object') {\n return false;\n }\n const classRegistryKey = getClassRegistryKey(input);\n if (classRegistryKey && classRegistryKey !== 'Object') {\n return true;\n }\n return false;\n}\n\nfunction isSerializeHandledByBuiltin(input: unknown) {\n return (!isRegistered(input) && (\n input === null ||\n input === undefined ||\n typeof input === 'boolean' ||\n typeof input === 'number' ||\n typeof input === 'string' ||\n input instanceof Boolean ||\n input instanceof Number ||\n input instanceof String ||\n input instanceof Date ||\n input instanceof RegExp ||\n input instanceof Blob ||\n input instanceof Error ||\n isArrayBuffer(input) ||\n isImageBitmap(input) ||\n ArrayBuffer.isView(input) ||\n input instanceof ImageData)\n );\n}\n\n/**\n * Serialize the given object for transfer to or from a web worker.\n *\n * For non-builtin types, recursively serialize each property (possibly\n * omitting certain properties - see register()), and package the result along\n * with the constructor's `name` so that the appropriate constructor can be\n * looked up in `deserialize()`.\n *\n * If a `transferables` array is provided, add any transferable objects (i.e.,\n * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed,\n * this should happen in the client code, before using serialize().)\n */\nexport function serialize(input: unknown, transferables?: Array | null): Serialized {\n if (isSerializeHandledByBuiltin(input)) {\n if (isArrayBuffer(input) || isImageBitmap(input)) {\n if (transferables) {\n transferables.push(input);\n }\n }\n if (ArrayBuffer.isView(input)) {\n const view = input;\n if (transferables) {\n transferables.push(view.buffer);\n }\n }\n if (input instanceof ImageData) {\n if (transferables) {\n transferables.push(input.data.buffer);\n }\n }\n return input;\n }\n\n if (Array.isArray(input)) {\n const serialized: Array = [];\n for (const item of input) {\n serialized.push(serialize(item, transferables));\n }\n return serialized;\n }\n\n if (typeof input !== 'object') {\n throw new Error(`can't serialize object of type ${typeof input}`);\n }\n const classRegistryKey = getClassRegistryKey(input);\n if (!classRegistryKey) {\n throw new Error(`can't serialize object of unregistered class ${input.constructor.name}`);\n }\n if (!registry[classRegistryKey]) throw new Error(`${classRegistryKey} is not registered.`);\n const {klass} = registry[classRegistryKey];\n const properties: SerializedObject = klass.serialize ?\n // (Temporary workaround) allow a class to provide static\n // `serialize()` and `deserialize()` methods to bypass the generic\n // approach.\n // This temporary workaround lets us use the generic serialization\n // approach for objects whose members include instances of dynamic\n // StructArray types. Once we refactor StructArray to be static,\n // we can remove this complexity.\n (klass.serialize(input, transferables) as SerializedObject) : {};\n\n if (!klass.serialize) {\n for (const key in input) {\n if (!input.hasOwnProperty(key)) continue; // eslint-disable-line no-prototype-builtins\n if (registry[classRegistryKey].omit.indexOf(key) >= 0) continue;\n const property = input[key];\n properties[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ?\n property :\n serialize(property, transferables);\n }\n if (input instanceof Error) {\n properties.message = input.message;\n }\n } else {\n if (transferables && properties === transferables[transferables.length - 1]) {\n throw new Error('statically serialized object won\\'t survive transfer of $name property');\n }\n }\n\n if (properties.$name) {\n throw new Error('$name property is reserved for worker serialization logic.');\n }\n if (classRegistryKey !== 'Object') {\n properties.$name = classRegistryKey;\n }\n\n return properties;\n}\n\nexport function deserialize(input: Serialized): unknown {\n if (isSerializeHandledByBuiltin(input)) {\n return input;\n }\n\n if (Array.isArray(input)) {\n return input.map(deserialize);\n }\n\n if (typeof input !== 'object') {\n throw new Error(`can't deserialize object of type ${typeof input}`);\n }\n const classRegistryKey = getClassRegistryKey(input) || 'Object';\n if (!registry[classRegistryKey]) {\n throw new Error(`can't deserialize unregistered class ${classRegistryKey}`);\n }\n const {klass} = registry[classRegistryKey];\n if (!klass) {\n throw new Error(`can't deserialize unregistered class ${classRegistryKey}`);\n }\n\n if (klass.deserialize) {\n return klass.deserialize(input);\n }\n\n const result = Object.create(klass.prototype);\n\n for (const key of Object.keys(input)) {\n if (key === '$name') continue;\n const value = (input as SerializedObject)[key];\n result[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ? value : deserialize(value);\n }\n\n return result;\n}\n","export class ZoomHistory {\n lastZoom: number;\n lastFloorZoom: number;\n lastIntegerZoom: number;\n lastIntegerZoomTime: number;\n first: boolean;\n\n constructor() {\n this.first = true;\n }\n\n update(z: number, now: number) {\n const floorZ = Math.floor(z);\n\n if (this.first) {\n this.first = false;\n this.lastIntegerZoom = floorZ;\n this.lastIntegerZoomTime = 0;\n this.lastZoom = z;\n this.lastFloorZoom = floorZ;\n return true;\n }\n\n if (this.lastFloorZoom > floorZ) {\n this.lastIntegerZoom = floorZ + 1;\n this.lastIntegerZoomTime = now;\n } else if (this.lastFloorZoom < floorZ) {\n this.lastIntegerZoom = floorZ;\n this.lastIntegerZoomTime = now;\n }\n\n if (z !== this.lastZoom) {\n this.lastZoom = z;\n this.lastFloorZoom = floorZ;\n return true;\n }\n\n return false;\n }\n}\n","// The following table comes from .\n// Keep it synchronized with .\n\ntype UnicodeBlockLookup = {[key: string]: (char: number) => boolean};\n\nexport const unicodeBlockLookup: UnicodeBlockLookup = {\n // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F,\n 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF,\n // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F,\n // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F,\n // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF,\n // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF,\n // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F,\n // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF,\n // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF,\n // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F,\n // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F,\n //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF,\n // 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF,\n //'Syriac': (char) => char >= 0x0700 && char <= 0x074F,\n // 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F,\n // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF,\n // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF,\n // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F,\n // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F,\n // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F,\n // 'Arabic Extended-B': (char) => char >= 0x0870 && char <= 0x089F,\n // 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF,\n // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F,\n // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF,\n // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F,\n // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF,\n // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F,\n // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF,\n // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F,\n // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF,\n // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F,\n // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF,\n // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F,\n // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF,\n // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF,\n // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F,\n // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF,\n 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF,\n // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F,\n // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F,\n // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF,\n // 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F,\n // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F,\n // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF,\n // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F,\n // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F,\n // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F,\n // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F,\n 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF,\n // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF,\n // 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF,\n // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F,\n // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F,\n // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF,\n // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF,\n // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F,\n // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF,\n // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF,\n // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F,\n // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF,\n // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF,\n // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F,\n // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F,\n // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F,\n // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF,\n // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF,\n // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF,\n // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F,\n // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF,\n // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF,\n // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF,\n // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF,\n 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F,\n // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F,\n // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF,\n // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF,\n 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F,\n 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F,\n // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF,\n // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF,\n 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF,\n 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F,\n 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F,\n 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF,\n // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F,\n // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F,\n 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF,\n 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF,\n // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF,\n // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF,\n // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF,\n // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF,\n // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F,\n // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF,\n // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF,\n 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF,\n // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F,\n // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F,\n // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF,\n // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F,\n // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F,\n // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF,\n // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF,\n // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F,\n // 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF,\n // 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF,\n 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF,\n 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F,\n // 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F,\n 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF,\n // 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F,\n // 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F,\n 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F,\n // 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF,\n 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF,\n // 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF,\n 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF,\n 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF,\n // 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF,\n 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF,\n // 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF,\n // 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F,\n // 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF,\n // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF,\n // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F,\n // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F,\n // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF,\n // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F,\n // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF,\n // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F,\n // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F,\n // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F,\n // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF,\n // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF,\n // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F,\n // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F,\n // 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F,\n // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF,\n // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF,\n // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F,\n // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F,\n // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF,\n // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF,\n // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F,\n // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F,\n // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF,\n // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF,\n // 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF,\n // 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF,\n // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F,\n // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF,\n // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF,\n 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF,\n // 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF,\n // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F,\n // 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF,\n // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F,\n 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F,\n // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F,\n 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F,\n 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F,\n // 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF,\n 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF\n // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF,\n // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F,\n // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF,\n // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F,\n // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F,\n // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF,\n // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF,\n // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F,\n // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF,\n // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF,\n // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F,\n // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F,\n // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F,\n // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F,\n // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF,\n // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F,\n // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F,\n // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF,\n // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF,\n // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F,\n // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F,\n // 'Vithkuqi': (char) => char >= 0x10570 && char <= 0x105BF,\n // 'Todhri': (char) => char >= 0x105C0 && char <= 0x105FF,\n // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F,\n // 'Latin Extended-F': (char) => char >= 0x10780 && char <= 0x107BF,\n // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F,\n // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F,\n // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F,\n // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF,\n // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF,\n // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F,\n // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F,\n // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F,\n // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF,\n // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F,\n // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F,\n // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F,\n // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF,\n // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F,\n // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F,\n // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F,\n // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF,\n // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F,\n // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF,\n // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F,\n // 'Garay': (char) => char >= 0x10D40 && char <= 0x10D8F,\n // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F,\n // 'Yezidi': (char) => char >= 0x10E80 && char <= 0x10EBF,\n // 'Arabic Extended-C': (char) => char >= 0x10EC0 && char <= 0x10EFF,\n // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F,\n // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F,\n // 'Old Uyghur': (char) => char >= 0x10F70 && char <= 0x10FAF,\n // 'Chorasmian': (char) => char >= 0x10FB0 && char <= 0x10FDF,\n // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF,\n // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F,\n // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF,\n // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF,\n // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F,\n // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F,\n // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF,\n // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF,\n // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F,\n // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF,\n // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF,\n // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F,\n // 'Tulu-Tigalari': (char) => char >= 0x11380 && char <= 0x113FF,\n // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F,\n // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF,\n // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF,\n // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F,\n // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F,\n // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF,\n // 'Myanmar Extended-C': (char) => char >= 0x116D0 && char <= 0x116FF,\n // 'Ahom': (char) => char >= 0x11700 && char <= 0x1174F,\n // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F,\n // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF,\n // 'Dives Akuru': (char) => char >= 0x11900 && char <= 0x1195F,\n // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF,\n // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F,\n // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF,\n // 'Unified Canadian Aboriginal Syllabics Extended-A': (char) => char >= 0x11AB0 && char <= 0x11ABF,\n // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF,\n // 'Devanagari Extended-A': (char) => char >= 0x11B00 && char <= 0x11B5F,\n // 'Sunuwar': (char) => char >= 0x11BC0 && char <= 0x11BFF,\n // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F,\n // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF,\n // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F,\n // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF,\n // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF,\n // 'Kawi': (char) => char >= 0x11F00 && char <= 0x11F5F,\n // 'Lisu Supplement': (char) => char >= 0x11FB0 && char <= 0x11FBF,\n // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF,\n // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF,\n // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F,\n // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F,\n // 'Cypro-Minoan': (char) => char >= 0x12F90 && char <= 0x12FFF,\n // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F,\n // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1345F,\n // 'Egyptian Hieroglyphs Extended-A': (char) => char >= 0x13460 && char <= 0x143FF,\n // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F,\n // 'Gurung Khema': (char) => char >= 0x16100 && char <= 0x1613F,\n // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F,\n // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F,\n // 'Tangsa': (char) => char >= 0x16A70 && char <= 0x16ACF,\n // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF,\n // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F,\n // 'Kirat Rai': (char) => char >= 0x16D40 && char <= 0x16D7F,\n // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F,\n // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F,\n // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF,\n // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF,\n // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF,\n // 'Khitan Small Script': (char) => char >= 0x18B00 && char <= 0x18CFF,\n // 'Tangut Supplement': (char) => char >= 0x18D00 && char <= 0x18D7F,\n // 'Kana Extended-B': (char) => char >= 0x1AFF0 && char <= 0x1AFFF,\n // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF,\n // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F,\n // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F,\n // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF,\n // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F,\n // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF,\n // 'Symbols for Legacy Computing Supplement': (char) => char >= 0x1CC00 && char <= 0x1CEBF,\n // 'Znamenny Musical Notation': (char) => char >= 0x1CF00 && char <= 0x1CFCF,\n // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF,\n // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF,\n // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F,\n // 'Kaktovik Numerals': (char) => char >= 0x1D2C0 && char <= 0x1D2DF,\n // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF,\n // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F,\n // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F,\n // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF,\n // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF,\n // 'Latin Extended-G': (char) => char >= 0x1DF00 && char <= 0x1DFFF,\n // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F,\n // 'Cyrillic Extended-D': (char) => char >= 0x1E030 && char <= 0x1E08F,\n // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F,\n // 'Toto': (char) => char >= 0x1E290 && char <= 0x1E2BF,\n // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF,\n // 'Nag Mundari': (char) => char >= 0x1E4D0 && char <= 0x1E4FF,\n // 'Ol Onal': (char) => char >= 0x1E5D0 && char <= 0x1E5FF,\n // 'Ethiopic Extended-B': (char) => char >= 0x1E7E0 && char <= 0x1E7FF,\n // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF,\n // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F,\n // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF,\n // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F,\n // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF,\n // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F,\n // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F,\n // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF,\n // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF,\n // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF,\n // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF,\n // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F,\n // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F,\n // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF,\n // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F,\n // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF,\n // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF,\n // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF,\n // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F,\n // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF,\n // 'Symbols for Legacy Computing': (char) => char >= 0x1FB00 && char <= 0x1FBFF,\n // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF,\n // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F,\n // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F,\n // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF,\n // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF,\n // 'CJK Unified Ideographs Extension I': (char) => char >= 0x2EBF0 && char <= 0x2EE5F,\n // 'CJK Unified Ideographs Extension G': (char) => char >= 0x30000 && char <= 0x3134F,\n // 'CJK Unified Ideographs Extension H': (char) => char >= 0x31350 && char <= 0x323AF,\n // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F,\n // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F,\n // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF,\n // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF,\n // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF,\n};\n","/* eslint-disable new-cap */\n\nimport {unicodeBlockLookup as isChar} from './is_char_in_unicode_block';\n\nexport function allowsIdeographicBreaking(chars: string) {\n for (const char of chars) {\n if (!charAllowsIdeographicBreaking(char.charCodeAt(0))) return false;\n }\n return true;\n}\n\nexport function allowsVerticalWritingMode(chars: string) {\n for (const char of chars) {\n if (charHasUprightVerticalOrientation(char.charCodeAt(0))) return true;\n }\n return false;\n}\n\nexport function allowsLetterSpacing(chars: string) {\n for (const char of chars) {\n if (!charAllowsLetterSpacing(char.charCodeAt(0))) return false;\n }\n return true;\n}\n\n/**\n * Returns a regular expression matching the given script codes, excluding any\n * code that the execution environment lacks support for in regular expressions.\n */\nfunction sanitizedRegExpFromScriptCodes(scriptCodes: Array): RegExp {\n const supportedPropertyEscapes = scriptCodes.map(code => {\n try {\n return new RegExp(`\\\\p{sc=${code}}`, 'u').source;\n } catch (e) {\n return null;\n }\n }).filter(pe => pe);\n return new RegExp(supportedPropertyEscapes.join('|'), 'u');\n}\n\n/**\n * ISO 15924 script codes of scripts that disallow letter spacing as of Unicode\n * 16.0.0.\n *\n * In general, cursive scripts are incompatible with letter spacing.\n */\nconst cursiveScriptCodes = [\n 'Arab', // Arabic\n 'Dupl', // Duployan\n 'Mong', // Mongolian\n 'Ougr', // Old Uyghur\n 'Syrc', // Syriac\n];\n\nconst cursiveScriptRegExp = sanitizedRegExpFromScriptCodes(cursiveScriptCodes);\n\nexport function charAllowsLetterSpacing(char: number) {\n return !cursiveScriptRegExp.test(String.fromCodePoint(char));\n}\n\n/**\n * ISO 15924 script codes of scripts that allow ideographic line breaking beyond\n * the CJKV scripts that are considered ideographic in Unicode 16.0.0.\n */\nconst ideographicBreakingScriptCodes = [\n 'Bopo', // Bopomofo\n 'Hani', // Han\n 'Hira', // Hiragana\n 'Kana', // Katakana\n 'Kits', // Khitan Small Script\n 'Nshu', // Nushu\n 'Tang', // Tangut\n 'Yiii', // Yi\n];\n\nconst ideographicBreakingRegExp = sanitizedRegExpFromScriptCodes(ideographicBreakingScriptCodes);\n\nexport function charAllowsIdeographicBreaking(char: number) {\n // Return early for characters outside all ideographic ranges.\n if (char < 0x2E80) return false;\n\n if (isChar['CJK Compatibility Forms'](char)) return true;\n if (isChar['CJK Compatibility'](char)) return true;\n if (isChar['CJK Strokes'](char)) return true;\n if (isChar['CJK Symbols and Punctuation'](char)) return true;\n if (isChar['Enclosed CJK Letters and Months'](char)) return true;\n if (isChar['Halfwidth and Fullwidth Forms'](char)) return true;\n if (isChar['Ideographic Description Characters'](char)) return true;\n if (isChar['Vertical Forms'](char)) return true;\n return ideographicBreakingRegExp.test(String.fromCodePoint(char));\n}\n\n// The following logic comes from\n// .\n// Keep it synchronized with\n// .\n// The data file denotes with “U” or “Tu” any codepoint that may be drawn\n// upright in vertical text but does not distinguish between upright and\n// “neutral” characters.\n\n// Blocks in the Unicode supplementary planes are excluded from this module due\n// to .\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * upright orientation.\n *\n * A character has upright orientation if it is drawn upright (unrotated)\n * whether the line is oriented horizontally or vertically, even if both\n * adjacent characters can be rotated. For example, a Chinese character is\n * always drawn upright. An uprightly oriented character causes an adjacent\n * “neutral” character to be drawn upright as well.\n */\nexport function charHasUprightVerticalOrientation(char: number) {\n if (char === 0x02EA /* modifier letter yin departing tone mark */ ||\n char === 0x02EB /* modifier letter yang departing tone mark */) {\n return true;\n }\n\n // Return early for characters outside all ranges whose characters remain\n // upright in vertical writing mode.\n if (char < 0x1100) return false;\n\n if (isChar['CJK Compatibility Forms'](char)) {\n if (!((char >= 0xFE49 /* dashed overline */ && char <= 0xFE4F) /* wavy low line */)) {\n return true;\n }\n }\n if (isChar['CJK Compatibility'](char)) return true;\n if (isChar['CJK Strokes'](char)) return true;\n if (isChar['CJK Symbols and Punctuation'](char)) {\n if (!((char >= 0x3008 /* left angle bracket */ && char <= 0x3011) /* right black lenticular bracket */) &&\n !((char >= 0x3014 /* left tortoise shell bracket */ && char <= 0x301F) /* low double prime quotation mark */) &&\n char !== 0x3030 /* wavy dash */) {\n return true;\n }\n }\n if (isChar['Enclosed CJK Letters and Months'](char)) return true;\n if (isChar['Ideographic Description Characters'](char)) return true;\n if (isChar['Kanbun'](char)) return true;\n if (isChar['Katakana'](char)) {\n if (char !== 0x30FC /* katakana-hiragana prolonged sound mark */) {\n return true;\n }\n }\n if (isChar['Halfwidth and Fullwidth Forms'](char)) {\n if (char !== 0xFF08 /* fullwidth left parenthesis */ &&\n char !== 0xFF09 /* fullwidth right parenthesis */ &&\n char !== 0xFF0D /* fullwidth hyphen-minus */ &&\n !((char >= 0xFF1A /* fullwidth colon */ && char <= 0xFF1E) /* fullwidth greater-than sign */) &&\n char !== 0xFF3B /* fullwidth left square bracket */ &&\n char !== 0xFF3D /* fullwidth right square bracket */ &&\n char !== 0xFF3F /* fullwidth low line */ &&\n !(char >= 0xFF5B /* fullwidth left curly bracket */ && char <= 0xFFDF) &&\n char !== 0xFFE3 /* fullwidth macron */ &&\n !(char >= 0xFFE8 /* halfwidth forms light vertical */ && char <= 0xFFEF)) {\n return true;\n }\n }\n if (isChar['Small Form Variants'](char)) {\n if (!((char >= 0xFE58 /* small em dash */ && char <= 0xFE5E) /* small right tortoise shell bracket */) &&\n !((char >= 0xFE63 /* small hyphen-minus */ && char <= 0xFE66) /* small equals sign */)) {\n return true;\n }\n }\n if (isChar['Vertical Forms'](char)) return true;\n if (isChar['Yijing Hexagram Symbols'](char)) return true;\n\n if (/* Canadian Aboriginal */ /\\p{sc=Cans}/u.test(String.fromCodePoint(char))) return true;\n if (/* Hangul */ /\\p{sc=Hang}/u.test(String.fromCodePoint(char))) return true;\n if (ideographicBreakingRegExp.test(String.fromCodePoint(char))) return true;\n\n return false;\n}\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * neutral orientation.\n *\n * A character has neutral orientation if it may be drawn rotated or unrotated\n * when the line is oriented vertically, depending on the orientation of the\n * adjacent characters. For example, along a vertically oriented line, the vulgar\n * fraction ½ is drawn upright among Chinese characters but rotated among Latin\n * letters. A neutrally oriented character does not influence whether an\n * adjacent character is drawn upright or rotated.\n */\nexport function charHasNeutralVerticalOrientation(char: number) {\n if (isChar['Latin-1 Supplement'](char)) {\n if (char === 0x00A7 /* section sign */ ||\n char === 0x00A9 /* copyright sign */ ||\n char === 0x00AE /* registered sign */ ||\n char === 0x00B1 /* plus-minus sign */ ||\n char === 0x00BC /* vulgar fraction one quarter */ ||\n char === 0x00BD /* vulgar fraction one half */ ||\n char === 0x00BE /* vulgar fraction three quarters */ ||\n char === 0x00D7 /* multiplication sign */ ||\n char === 0x00F7 /* division sign */) {\n return true;\n }\n }\n if (isChar['General Punctuation'](char)) {\n if (char === 0x2016 /* double vertical line */ ||\n char === 0x2020 /* dagger */ ||\n char === 0x2021 /* double dagger */ ||\n char === 0x2030 /* per mille sign */ ||\n char === 0x2031 /* per ten thousand sign */ ||\n char === 0x203B /* reference mark */ ||\n char === 0x203C /* double exclamation mark */ ||\n char === 0x2042 /* asterism */ ||\n char === 0x2047 /* double question mark */ ||\n char === 0x2048 /* question exclamation mark */ ||\n char === 0x2049 /* exclamation question mark */ ||\n char === 0x2051 /* two asterisks aligned vertically */) {\n return true;\n }\n }\n if (isChar['Letterlike Symbols'](char)) return true;\n if (isChar['Number Forms'](char)) return true;\n if (isChar['Miscellaneous Technical'](char)) {\n if ((char >= 0x2300 /* diameter sign */ && char <= 0x2307 /* wavy line */) ||\n (char >= 0x230C /* bottom right crop */ && char <= 0x231F /* bottom right corner */) ||\n (char >= 0x2324 /* up arrowhead between two horizontal bars */ && char <= 0x2328 /* keyboard */) ||\n char === 0x232B /* erase to the left */ ||\n (char >= 0x237D /* shouldered open box */ && char <= 0x239A /* clear screen symbol */) ||\n (char >= 0x23BE /* dentistry symbol light vertical and top right */ && char <= 0x23CD /* square foot */) ||\n char === 0x23CF /* eject symbol */ ||\n (char >= 0x23D1 /* metrical breve */ && char <= 0x23DB /* fuse */) ||\n (char >= 0x23E2 /* white trapezium */ && char <= 0x23FF)) {\n return true;\n }\n }\n if (isChar['Control Pictures'](char) && char !== 0x2423 /* open box */) return true;\n if (isChar['Optical Character Recognition'](char)) return true;\n if (isChar['Enclosed Alphanumerics'](char)) return true;\n if (isChar['Geometric Shapes'](char)) return true;\n if (isChar['Miscellaneous Symbols'](char)) {\n if (!((char >= 0x261A /* black left pointing index */ && char <= 0x261F) /* white down pointing index */)) {\n return true;\n }\n }\n if (isChar['Miscellaneous Symbols and Arrows'](char)) {\n if ((char >= 0x2B12 /* square with top half black */ && char <= 0x2B2F /* white vertical ellipse */) ||\n (char >= 0x2B50 /* white medium star */ && char <= 0x2B59 /* heavy circled saltire */) ||\n (char >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && char <= 0x2BEB)) {\n return true;\n }\n }\n if (isChar['CJK Symbols and Punctuation'](char)) return true;\n if (isChar['Katakana'](char)) return true;\n if (isChar['Private Use Area'](char)) return true;\n if (isChar['CJK Compatibility Forms'](char)) return true;\n if (isChar['Small Form Variants'](char)) return true;\n if (isChar['Halfwidth and Fullwidth Forms'](char)) return true;\n\n if (char === 0x221E /* infinity */ ||\n char === 0x2234 /* therefore */ ||\n char === 0x2235 /* because */ ||\n (char >= 0x2700 /* black safety scissors */ && char <= 0x2767 /* rotated floral heart bullet */) ||\n (char >= 0x2776 /* dingbat negative circled digit one */ && char <= 0x2793 /* dingbat negative circled sans-serif number ten */) ||\n char === 0xFFFC /* object replacement character */ ||\n char === 0xFFFD /* replacement character */) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * rotated orientation.\n *\n * A character has rotated orientation if it is drawn rotated when the line is\n * oriented vertically, even if both adjacent characters are upright. For\n * example, a Latin letter is drawn rotated along a vertical line. A rotated\n * character causes an adjacent “neutral” character to be drawn rotated as well.\n */\nexport function charHasRotatedVerticalOrientation(char: number) {\n return !(charHasUprightVerticalOrientation(char) ||\n charHasNeutralVerticalOrientation(char));\n}\n\nexport function charInComplexShapingScript(char: number) {\n return /\\p{sc=Arab}/u.test(String.fromCodePoint(char));\n}\n\n/**\n * ISO 15924 script codes of scripts that are primarily written horizontally\n * right-to-left according to Unicode 16.0.0.\n */\nconst rtlScriptCodes = [\n 'Adlm', // Adlam\n 'Arab', // Arabic\n 'Armi', // Imperial Aramaic\n 'Avst', // Avestan\n 'Chrs', // Chorasmian\n 'Cprt', // Cypriot\n 'Egyp', // Egyptian Hieroglyphs\n 'Elym', // Elymaic\n 'Gara', // Garay\n 'Hatr', // Hatran\n 'Hebr', // Hebrew\n 'Hung', // Old Hungarian\n 'Khar', // Kharoshthi\n 'Lydi', // Lydian\n 'Mand', // Mandaic\n 'Mani', // Manichaean\n 'Mend', // Mende Kikakui\n 'Merc', // Meroitic Cursive\n 'Mero', // Meroitic Hieroglyphs\n 'Narb', // Old North Arabian\n 'Nbat', // Nabataean\n 'Nkoo', // NKo\n 'Orkh', // Old Turkic\n 'Palm', // Palmyrene\n 'Phli', // Inscriptional Pahlavi\n 'Phlp', // Psalter Pahlavi\n 'Phnx', // Phoenician\n 'Prti', // Inscriptional Parthian\n 'Rohg', // Hanifi Rohingya\n 'Samr', // Samaritan\n 'Sarb', // Old South Arabian\n 'Sogo', // Old Sogdian\n 'Syrc', // Syriac\n 'Thaa', // Thaana\n 'Todr', // Todhri\n 'Yezi', // Yezidi\n];\n\nconst rtlScriptRegExp = sanitizedRegExpFromScriptCodes(rtlScriptCodes);\n\nexport function charInRTLScript(char: number) {\n return rtlScriptRegExp.test(String.fromCodePoint(char));\n}\n\nexport function charInSupportedScript(char: number, canRenderRTL: boolean) {\n // This is a rough heuristic: whether we \"can render\" a script\n // actually depends on the properties of the font being used\n // and whether differences from the ideal rendering are considered\n // semantically significant.\n\n // Even in Latin script, we \"can't render\" combinations such as the fi\n // ligature, but we don't consider that semantically significant.\n if (!canRenderRTL && charInRTLScript(char)) {\n return false;\n }\n if ((char >= 0x0900 && char <= 0x0DFF) ||\n // Main blocks for Indic scripts and Sinhala\n (char >= 0x0F00 && char <= 0x109F) ||\n // Main blocks for Tibetan and Myanmar\n isChar['Khmer'](char)) {\n // These blocks cover common scripts that require\n // complex text shaping, based on unicode script metadata:\n // https://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt\n // where \"Web Rank <= 32\" \"Shaping Required = YES\"\n return false;\n }\n return true;\n}\n\nexport function stringContainsRTLText(chars: string): boolean {\n for (const char of chars) {\n if (charInRTLScript(char.charCodeAt(0))) {\n return true;\n }\n }\n return false;\n}\n\nexport function isStringInSupportedScript(chars: string, canRenderRTL: boolean) {\n for (const char of chars) {\n if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) {\n return false;\n }\n }\n return true;\n}\n","import {PluginState, RTLPluginStatus} from './rtl_text_plugin_status';\n\nexport interface RTLTextPlugin {\n applyArabicShaping: (a: string) => string;\n processBidirectionalText: ((b: string, a: Array) => Array);\n processStyledBidirectionalText: ((c: string, b: Array, a: Array) => Array<[string, Array]>);\n}\n\nclass RTLWorkerPlugin implements RTLTextPlugin {\n applyArabicShaping: (a: string) => string = null;\n processBidirectionalText: ((b: string, a: Array) => Array) = null;\n processStyledBidirectionalText: ((c: string, b: Array, a: Array) => Array<[string, Array]>) = null;\n pluginStatus: RTLPluginStatus = 'unavailable';\n pluginURL: string = null;\n\n setState(state: PluginState) {\n this.pluginStatus = state.pluginStatus;\n this.pluginURL = state.pluginURL;\n }\n\n getState(): PluginState {\n return {\n pluginStatus: this.pluginStatus,\n pluginURL: this.pluginURL\n };\n }\n\n setMethods(rtlTextPlugin: RTLTextPlugin) {\n this.applyArabicShaping = rtlTextPlugin.applyArabicShaping;\n this.processBidirectionalText = rtlTextPlugin.processBidirectionalText;\n this.processStyledBidirectionalText = rtlTextPlugin.processStyledBidirectionalText;\n }\n\n isParsed(): boolean {\n return this.applyArabicShaping != null &&\n this.processBidirectionalText != null &&\n this.processStyledBidirectionalText != null;\n }\n\n getPluginURL(): string {\n return this.pluginURL;\n }\n\n getRTLTextPluginStatus() {\n return this.pluginStatus;\n }\n}\n\nexport const rtlWorkerPlugin = new RTLWorkerPlugin();\n","import {ZoomHistory} from './zoom_history';\nimport {isStringInSupportedScript} from '../util/script_detection';\nimport {rtlWorkerPlugin} from '../source/rtl_text_plugin_worker';\n\nimport type {TransitionSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport type CrossfadeParameters = {\n fromScale: number;\n toScale: number;\n t: number;\n};\n\n/**\n * @internal\n * A parameter that can be evaluated to a value\n */\nexport class EvaluationParameters {\n zoom: number;\n now: number;\n fadeDuration: number;\n zoomHistory: ZoomHistory;\n transition: TransitionSpecification;\n\n // \"options\" may also be another EvaluationParameters to copy, see CrossFadedProperty.possiblyEvaluate\n constructor(zoom: number, options?: any) {\n this.zoom = zoom;\n\n if (options) {\n this.now = options.now;\n this.fadeDuration = options.fadeDuration;\n this.zoomHistory = options.zoomHistory;\n this.transition = options.transition;\n } else {\n this.now = 0;\n this.fadeDuration = 0;\n this.zoomHistory = new ZoomHistory();\n this.transition = {};\n }\n }\n\n isSupportedScript(str: string): boolean {\n return isStringInSupportedScript(str, rtlWorkerPlugin.getRTLTextPluginStatus() === 'loaded');\n }\n\n crossFadingFactor() {\n if (this.fadeDuration === 0) {\n return 1;\n } else {\n return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1);\n }\n }\n\n getCrossfadeParameters(): CrossfadeParameters {\n const z = this.zoom;\n const fraction = z - Math.floor(z);\n const t = this.crossFadingFactor();\n\n return z > this.zoomHistory.lastIntegerZoom ?\n {fromScale: 2, toScale: 1, t: fraction + (1 - fraction) * t} :\n {fromScale: 0.5, toScale: 1, t: 1 - (1 - t) * fraction};\n }\n}\n","import {clone, extend, easeCubicInOut} from '../util/util';\nimport {interpolates, Color, StylePropertySpecification, normalizePropertyExpression,\n Feature,\n FeatureState,\n StylePropertyExpression,\n SourceExpression,\n CompositeExpression, TransitionSpecification,\n PropertyValueSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {register} from '../util/web_worker_transfer';\nimport {EvaluationParameters} from './evaluation_parameters';\n\nimport {CanonicalTileID} from '../source/tile_id';\n\ntype TimePoint = number;\n\n/**\n * A from-to type\n */\nexport type CrossFaded = {\n to: T;\n from: T;\n};\n\n/**\n * @internal\n * Implementations of the `Property` interface:\n *\n * * Hold metadata about a property that's independent of any specific value: stuff like the type of the value,\n * the default value, etc. This comes from the style specification JSON.\n * * Define behavior that needs to be polymorphic across different properties: \"possibly evaluating\"\n * an input value (see below), and interpolating between two possibly-evaluted values.\n *\n * The type `T` is the fully-evaluated value type (e.g. `number`, `string`, `Color`).\n * The type `R` is the intermediate \"possibly evaluated\" value type. See below.\n *\n * There are two main implementations of the interface -- one for properties that allow data-driven values,\n * and one for properties that don't. There are a few \"special case\" implementations as well: one for properties\n * which cross-fade between two values rather than interpolating, one for `heatmap-color` and `line-gradient`,\n * and one for `light-position`.\n */\nexport interface Property {\n specification: StylePropertySpecification;\n possiblyEvaluate(\n value: PropertyValue,\n parameters: EvaluationParameters,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): R;\n interpolate(a: R, b: R, t: number): R;\n}\n\n/**\n * @internal\n * `PropertyValue` represents the value part of a property key-value unit. It's used to represent both\n * paint and layout property values, and regardless of whether or not their property supports data-driven\n * expressions.\n *\n * `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the\n * following:\n *\n * * A constant value of the type appropriate for the property\n * * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions)\n * * An expression which produces a value of that type\n * * \"undefined\"/\"not present\", in which case the property is assumed to take on its default value.\n *\n * In addition to storing the original input value, `PropertyValue` also stores a normalized representation,\n * effectively treating functions as if they are expressions, and constant or default values as if they are\n * (constant) expressions.\n */\nexport class PropertyValue {\n property: Property;\n value: PropertyValueSpecification | void;\n expression: StylePropertyExpression;\n\n constructor(property: Property, value: PropertyValueSpecification | void) {\n this.property = property;\n this.value = value;\n this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification);\n }\n\n isDataDriven(): boolean {\n return this.expression.kind === 'source' || this.expression.kind === 'composite';\n }\n\n possiblyEvaluate(\n parameters: EvaluationParameters,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): R {\n return this.property.possiblyEvaluate(this, parameters, canonical, availableImages);\n }\n}\n\nexport type TransitionParameters = {\n now: TimePoint;\n transition: TransitionSpecification;\n};\n\n/**\n * @internal\n * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between\n * old and new value. The duration of the transition, and the delay before it begins, is configurable.\n *\n * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition\n * configuration.\n *\n * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values:\n * `TransitioningPropertyValue`.\n */\nclass TransitionablePropertyValue {\n property: Property;\n value: PropertyValue;\n transition: TransitionSpecification | void;\n\n constructor(property: Property) {\n this.property = property;\n this.value = new PropertyValue(property, undefined);\n }\n\n transitioned(parameters: TransitionParameters, prior: TransitioningPropertyValue): TransitioningPropertyValue {\n return new TransitioningPropertyValue(this.property, this.value, prior,\n extend({}, parameters.transition, this.transition), parameters.now);\n }\n\n untransitioned(): TransitioningPropertyValue {\n return new TransitioningPropertyValue(this.property, this.value, null, {}, 0);\n }\n}\n\n/**\n * @internal\n * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a\n * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a\n * `Transitioning` instance for the same set of properties.\n */\nexport class Transitionable {\n _properties: Properties;\n _values: {[K in keyof Props]: TransitionablePropertyValue};\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitionablePropertyValues) as any);\n }\n\n getValue(name: S): PropertyValueSpecification | void {\n return clone(this._values[name].value.value);\n }\n\n setValue(name: S, value: PropertyValueSpecification | void) {\n if (!Object.prototype.hasOwnProperty.call(this._values, name)) {\n this._values[name] = new TransitionablePropertyValue(this._values[name].property);\n }\n // Note that we do not _remove_ an own property in the case where a value is being reset\n // to the default: the transition might still be non-default.\n this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value));\n }\n\n getTransition(name: S): TransitionSpecification | void {\n return clone(this._values[name].transition);\n }\n\n setTransition(name: S, value: TransitionSpecification | void) {\n if (!Object.prototype.hasOwnProperty.call(this._values, name)) {\n this._values[name] = new TransitionablePropertyValue(this._values[name].property);\n }\n this._values[name].transition = clone(value) || undefined;\n }\n\n serialize() {\n const result: any = {};\n for (const property of Object.keys(this._values)) {\n const value = this.getValue(property as keyof Props);\n if (value !== undefined) {\n result[property] = value;\n }\n\n const transition = this.getTransition(property as keyof Props);\n if (transition !== undefined) {\n result[`${property}-transition`] = transition;\n }\n }\n return result;\n }\n\n transitioned(parameters: TransitionParameters, prior: Transitioning): Transitioning {\n const result = new Transitioning(this._properties);\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].transitioned(parameters, prior._values[property]);\n }\n return result;\n }\n\n untransitioned(): Transitioning {\n const result = new Transitioning(this._properties);\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].untransitioned();\n }\n return result;\n }\n}\n\n/**\n * @internal\n * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint\n * property value. In this step, transitions between old and new values are handled: as long as the transition is in\n * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and\n * the new value based on the current time and the configured transition duration and delay. The product is the next\n * step in the evaluation chain: the \"possibly evaluated\" result type `R`. See below for more on this concept.\n */\nclass TransitioningPropertyValue {\n property: Property;\n value: PropertyValue;\n prior: TransitioningPropertyValue;\n begin: TimePoint;\n end: TimePoint;\n\n constructor(property: Property,\n value: PropertyValue,\n prior: TransitioningPropertyValue,\n transition: TransitionSpecification,\n now: TimePoint) {\n this.property = property;\n this.value = value;\n this.begin = now + transition.delay || 0;\n this.end = this.begin + transition.duration || 0;\n if (property.specification.transition && (transition.delay || transition.duration)) {\n this.prior = prior;\n }\n }\n\n possiblyEvaluate(\n parameters: EvaluationParameters,\n canonical: CanonicalTileID,\n availableImages: Array\n ): R {\n const now = parameters.now || 0;\n const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages);\n const prior = this.prior;\n if (!prior) {\n // No prior value.\n return finalValue;\n } else if (now > this.end) {\n // Transition from prior value is now complete.\n this.prior = null;\n return finalValue;\n } else if (this.value.isDataDriven()) {\n // Transitions to data-driven properties are not supported.\n // We snap immediately to the data-driven value so that, when we perform layout,\n // we see the data-driven function and can use it to populate vertex buffers.\n this.prior = null;\n return finalValue;\n } else if (now < this.begin) {\n // Transition hasn't started yet.\n return prior.possiblyEvaluate(parameters, canonical, availableImages);\n } else {\n // Interpolate between recursively-calculated prior value and final.\n const t = (now - this.begin) / (this.end - this.begin);\n return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t));\n }\n }\n}\n\n/**\n * @internal\n * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a\n * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a\n * `PossiblyEvaluated` instance for the same set of properties.\n */\nexport class Transitioning {\n _properties: Properties;\n _values: {[K in keyof Props]: PossiblyEvaluatedPropertyValue};\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitioningPropertyValues) as any);\n }\n\n possiblyEvaluate(\n parameters: EvaluationParameters,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): PossiblyEvaluated {\n const result = new PossiblyEvaluated(this._properties);\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);\n }\n return result;\n }\n\n hasTransition() {\n for (const property of Object.keys(this._values)) {\n if (this._values[property].prior) {\n return true;\n }\n }\n return false;\n }\n}\n\n// ------- Layout -------\n\n/**\n * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than\n * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then\n * fully evaluated.\n *\n * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a\n * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a\n * `PossiblyEvaluated` instance for the same set of properties.\n */\nexport class Layout {\n _properties: Properties;\n _values: {[K in keyof Props]: PropertyValue>};\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultPropertyValues) as any);\n }\n\n hasValue(name: S) {\n return this._values[name].value !== undefined;\n }\n\n getValue(name: S) {\n return clone(this._values[name].value);\n }\n\n setValue(name: S, value: any) {\n this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value)) as any;\n }\n\n serialize() {\n const result: any = {};\n for (const property of Object.keys(this._values)) {\n const value = this.getValue(property as keyof Props);\n if (value !== undefined) {\n result[property] = value;\n }\n }\n return result;\n }\n\n possiblyEvaluate(\n parameters: EvaluationParameters,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): PossiblyEvaluated {\n const result = new PossiblyEvaluated(this._properties);\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);\n }\n return result;\n }\n}\n\n// ------- PossiblyEvaluated -------\n\n/**\n * \"Possibly evaluated value\" is an intermediate stage in the evaluation chain for both paint and layout property\n * values. The purpose of this stage is to optimize away unnecessary recalculations for data-driven properties. Code\n * which uses data-driven property values must assume that the value is dependent on feature data, and request that it\n * be evaluated for each feature. But when that property value is in fact a constant or camera function, the calculation\n * will not actually depend on the feature, and we can benefit from returning the prior result of having done the\n * evaluation once, ahead of time, in an intermediate step whose inputs are just the value and \"global\" parameters\n * such as current zoom level.\n *\n * `PossiblyEvaluatedValue` represents the three possible outcomes of this step: if the input value was a constant or\n * camera expression, then the \"possibly evaluated\" result is a constant value. Otherwise, the input value was either\n * a source or composite expression, and we must defer final evaluation until supplied a feature. We separate\n * the source and composite cases because they are handled differently when generating GL attributes, buffers, and\n * uniforms.\n *\n * Note that `PossiblyEvaluatedValue` (and `PossiblyEvaluatedPropertyValue`, below) are _not_ used for properties that\n * do not allow data-driven values. For such properties, we know that the \"possibly evaluated\" result is always a constant\n * scalar value. See below.\n */\ntype PossiblyEvaluatedValue = {\n kind: 'constant';\n value: T;\n} | SourceExpression | CompositeExpression;\n\n/**\n * @internal\n * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a\n * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply\n * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the\n * case where the input value was a constant or camera function.\n */\nexport class PossiblyEvaluatedPropertyValue {\n property: DataDrivenProperty;\n value: PossiblyEvaluatedValue;\n parameters: EvaluationParameters;\n\n constructor(property: DataDrivenProperty, value: PossiblyEvaluatedValue, parameters: EvaluationParameters) {\n this.property = property;\n this.value = value;\n this.parameters = parameters;\n }\n\n isConstant(): boolean {\n return this.value.kind === 'constant';\n }\n\n constantOr(value: T): T {\n if (this.value.kind === 'constant') {\n return this.value.value;\n } else {\n return value;\n }\n }\n\n evaluate(\n feature: Feature,\n featureState: FeatureState,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): T {\n return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages);\n }\n}\n\n/**\n * @internal\n * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a\n * given layer type.\n */\nexport class PossiblyEvaluated {\n _properties: Properties;\n _values: PossibleEvaluatedProps;\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = Object.create(properties.defaultPossiblyEvaluatedValues);\n }\n\n get(name: S): PossibleEvaluatedProps[S] {\n return this._values[name];\n }\n}\n\n/**\n * @internal\n * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions.\n * This restriction allows us to declare statically that the result of possibly evaluating this kind of property\n * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis.\n */\nexport class DataConstantProperty implements Property {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters): T {\n if (value.isDataDriven()) throw new Error('Value should not be data driven');\n return value.expression.evaluate(parameters);\n }\n\n interpolate(a: T, b: T, t: number): T {\n const interpolationType = this.specification.type as keyof typeof interpolates;\n const interpolationFn = interpolates[interpolationType] as ((from: T, to: T, t: number) => T) | undefined;\n if (interpolationFn) {\n return interpolationFn(a, b, t);\n } else {\n return a;\n }\n }\n}\n\n/**\n * @internal\n * An implementation of `Property` for properties that permit data-driven (source or composite) expressions.\n * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue`; obtaining\n * a scalar value `T` requires further evaluation on a per-feature basis.\n */\nexport class DataDrivenProperty implements Property> {\n specification: StylePropertySpecification;\n overrides: any;\n\n constructor(specification: StylePropertySpecification, overrides?: any) {\n this.specification = specification;\n this.overrides = overrides;\n }\n\n possiblyEvaluate(\n value: PropertyValue>,\n parameters: EvaluationParameters,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): PossiblyEvaluatedPropertyValue {\n if (value.expression.kind === 'constant' || value.expression.kind === 'camera') {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: value.expression.evaluate(parameters, null, {}, canonical, availableImages)}, parameters);\n } else {\n return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);\n }\n }\n\n interpolate(\n a: PossiblyEvaluatedPropertyValue,\n b: PossiblyEvaluatedPropertyValue,\n t: number\n ): PossiblyEvaluatedPropertyValue {\n // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values.\n if (a.value.kind !== 'constant' || b.value.kind !== 'constant') {\n return a;\n }\n\n // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in\n // FillStyleLayer#recalculate, which sets fill-outline-color to the fill-color value if the former\n // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the\n // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant\n // undefined value is the \"default value\" for fill-outline-color held in\n // `Properties#defaultPossiblyEvaluatedValues`, which serves as the prototype of\n // `PossiblyEvaluated#_values`.\n if (a.value.value === undefined || b.value.value === undefined) {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: undefined}, a.parameters);\n }\n\n const interpolationType = this.specification.type as keyof typeof interpolates;\n const interpolationFn = interpolates[interpolationType] as ((from: T, to: T, t: number) => T) | undefined;\n if (interpolationFn) {\n const interpolatedValue = interpolationFn(a.value.value, b.value.value, t);\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: interpolatedValue}, a.parameters);\n } else {\n return a;\n }\n }\n\n evaluate(\n value: PossiblyEvaluatedValue,\n parameters: EvaluationParameters,\n feature: Feature,\n featureState: FeatureState,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): T {\n if (value.kind === 'constant') {\n return value.value;\n } else {\n return value.evaluate(parameters, feature, featureState, canonical, availableImages);\n }\n }\n}\n\n/**\n * @internal\n * An implementation of `Property` for data driven `line-pattern` which are transitioned by cross-fading\n * rather than interpolation.\n */\n\nexport class CrossFadedDataDrivenProperty extends DataDrivenProperty> {\n\n possiblyEvaluate(\n value: PropertyValue, PossiblyEvaluatedPropertyValue>>,\n parameters: EvaluationParameters,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): PossiblyEvaluatedPropertyValue> {\n if (value.value === undefined) {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: undefined}, parameters);\n } else if (value.expression.kind === 'constant') {\n const evaluatedValue = value.expression.evaluate(parameters, null, {}, canonical, availableImages);\n const isImageExpression = value.property.specification.type as any === 'resolvedImage';\n const constantValue = isImageExpression && typeof evaluatedValue !== 'string' ? evaluatedValue.name : evaluatedValue;\n const constant = this._calculate(constantValue, constantValue, constantValue, parameters);\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: constant}, parameters);\n } else if (value.expression.kind === 'camera') {\n const cameraVal = this._calculate(\n value.expression.evaluate({zoom: parameters.zoom - 1.0}),\n value.expression.evaluate({zoom: parameters.zoom}),\n value.expression.evaluate({zoom: parameters.zoom + 1.0}),\n parameters);\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: cameraVal}, parameters);\n } else {\n // source or composite expression\n return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);\n }\n }\n\n evaluate(\n value: PossiblyEvaluatedValue>,\n globals: EvaluationParameters,\n feature: Feature,\n featureState: FeatureState,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): CrossFaded {\n if (value.kind === 'source') {\n const constant = value.evaluate(globals, feature, featureState, canonical, availableImages);\n return this._calculate(constant, constant, constant, globals);\n } else if (value.kind === 'composite') {\n return this._calculate(\n value.evaluate({zoom: Math.floor(globals.zoom) - 1.0}, feature, featureState),\n value.evaluate({zoom: Math.floor(globals.zoom)}, feature, featureState),\n value.evaluate({zoom: Math.floor(globals.zoom) + 1.0}, feature, featureState),\n globals);\n } else {\n return value.value;\n }\n }\n\n _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): CrossFaded {\n const z = parameters.zoom;\n return z > parameters.zoomHistory.lastIntegerZoom ? {from: min, to: mid} : {from: max, to: mid};\n }\n\n interpolate(a: PossiblyEvaluatedPropertyValue>): PossiblyEvaluatedPropertyValue> {\n return a;\n }\n}\n/**\n * @internal\n * An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading\n * rather than interpolation.\n */\nexport class CrossFadedProperty implements Property> {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(\n value: PropertyValue>,\n parameters: EvaluationParameters,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): CrossFaded {\n if (value.value === undefined) {\n return undefined;\n } else if (value.expression.kind === 'constant') {\n const constant = value.expression.evaluate(parameters, null, {}, canonical, availableImages);\n return this._calculate(constant, constant, constant, parameters);\n } else {\n return this._calculate(\n value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1.0), parameters)),\n value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)),\n value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1.0), parameters)),\n parameters);\n }\n }\n\n _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): CrossFaded {\n const z = parameters.zoom;\n return z > parameters.zoomHistory.lastIntegerZoom ? {from: min, to: mid} : {from: max, to: mid};\n }\n\n interpolate(a?: CrossFaded | null): CrossFaded {\n return a;\n }\n}\n\n/**\n * @internal\n * An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and\n * evaluation returns a boolean value in order to indicate its presence, but the real\n * evaluation happens in StyleLayer classes.\n */\n\nexport class ColorRampProperty implements Property {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(\n value: PropertyValue,\n parameters: EvaluationParameters,\n canonical?: CanonicalTileID,\n availableImages?: Array\n ): boolean {\n return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages);\n }\n\n interpolate(): boolean { return false; }\n}\n\n/**\n * @internal\n * `Properties` holds objects containing default values for the layout or paint property set of a given\n * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of\n * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid\n * doing work in the common case where a property has no explicit value set and should be considered to take\n * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over\n * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final\n * evaluations for defaults, the result of which will always be the same.\n */\nexport class Properties {\n properties: Props;\n defaultPropertyValues: {[K in keyof Props]: PropertyValue};\n defaultTransitionablePropertyValues: {[K in keyof Props]: TransitionablePropertyValue};\n defaultTransitioningPropertyValues: {[K in keyof Props]: TransitioningPropertyValue};\n defaultPossiblyEvaluatedValues: {[K in keyof Props]: PossiblyEvaluatedPropertyValue};\n overridableProperties: Array;\n\n constructor(properties: Props) {\n this.properties = properties;\n this.defaultPropertyValues = ({} as any);\n this.defaultTransitionablePropertyValues = ({} as any);\n this.defaultTransitioningPropertyValues = ({} as any);\n this.defaultPossiblyEvaluatedValues = ({} as any);\n this.overridableProperties = ([] as any);\n\n for (const property in properties) {\n const prop = properties[property] as any;\n if (prop.specification.overridable) {\n this.overridableProperties.push(property);\n }\n const defaultPropertyValue = this.defaultPropertyValues[property] =\n new PropertyValue(prop, undefined);\n const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] =\n new TransitionablePropertyValue(prop);\n this.defaultTransitioningPropertyValues[property] =\n defaultTransitionablePropertyValue.untransitioned();\n this.defaultPossiblyEvaluatedValues[property] =\n defaultPropertyValue.possiblyEvaluate({} as any);\n }\n }\n}\n\nregister('DataDrivenProperty', DataDrivenProperty);\nregister('DataConstantProperty', DataConstantProperty);\nregister('CrossFadedDataDrivenProperty', CrossFadedDataDrivenProperty);\nregister('CrossFadedProperty', CrossFadedProperty);\nregister('ColorRampProperty', ColorRampProperty);\n","import {filterObject} from '../util/util';\n\nimport {latest as styleSpec, supportsPropertyExpression} from '@maplibre/maplibre-gl-style-spec';\nimport {\n validateStyle,\n validateLayoutProperty,\n validatePaintProperty,\n emitValidationErrors\n} from './validate_style';\nimport {Evented} from '../util/evented';\nimport {Layout, Transitionable, Transitioning, Properties, PossiblyEvaluated, PossiblyEvaluatedPropertyValue} from './properties';\n\nimport type {Bucket} from '../data/bucket';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureFilter, FeatureState,\n LayerSpecification,\n FilterSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {TransitionParameters, PropertyValue} from './properties';\nimport {EvaluationParameters} from './evaluation_parameters';\nimport type {CrossfadeParameters} from './evaluation_parameters';\n\nimport type {Transform} from '../geo/transform';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer';\nimport type {Map} from '../ui/map';\nimport type {StyleSetterOptions} from './style';\nimport {mat4} from 'gl-matrix';\nimport type {VectorTileFeature} from '@mapbox/vector-tile';\n\nconst TRANSITION_SUFFIX = '-transition';\n\n/**\n * A base class for style layers\n */\nexport abstract class StyleLayer extends Evented {\n id: string;\n metadata: unknown;\n type: LayerSpecification['type'] | CustomLayerInterface['type'];\n source: string;\n sourceLayer: string;\n minzoom: number;\n maxzoom: number;\n filter: FilterSpecification | void;\n visibility: 'visible' | 'none' | void;\n _crossfadeParameters: CrossfadeParameters;\n\n _unevaluatedLayout: Layout;\n readonly layout: unknown;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n readonly paint: unknown;\n\n _featureFilter: FeatureFilter;\n\n readonly onAdd: ((map: Map) => void);\n readonly onRemove: ((map: Map) => void);\n\n queryRadius?(bucket: Bucket): number;\n queryIntersectsFeature?(\n queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number,\n pixelPosMatrix: mat4\n ): boolean | number;\n\n constructor(layer: LayerSpecification | CustomLayerInterface, properties: Readonly<{\n layout?: Properties;\n paint?: Properties;\n }>) {\n super();\n\n this.id = layer.id;\n this.type = layer.type;\n this._featureFilter = {filter: () => true, needGeometry: false};\n\n if (layer.type === 'custom') return;\n\n layer = (layer as any as LayerSpecification);\n\n this.metadata = layer.metadata;\n this.minzoom = layer.minzoom;\n this.maxzoom = layer.maxzoom;\n\n if (layer.type !== 'background') {\n this.source = layer.source;\n this.sourceLayer = layer['source-layer'];\n this.filter = layer.filter;\n }\n\n if (properties.layout) {\n this._unevaluatedLayout = new Layout(properties.layout);\n }\n\n if (properties.paint) {\n this._transitionablePaint = new Transitionable(properties.paint);\n\n for (const property in layer.paint) {\n this.setPaintProperty(property, layer.paint[property], {validate: false});\n }\n for (const property in layer.layout) {\n this.setLayoutProperty(property, layer.layout[property], {validate: false});\n }\n\n this._transitioningPaint = this._transitionablePaint.untransitioned();\n //$FlowFixMe\n this.paint = new PossiblyEvaluated(properties.paint);\n }\n }\n\n getCrossfadeParameters() {\n return this._crossfadeParameters;\n }\n\n getLayoutProperty(name: string) {\n if (name === 'visibility') {\n return this.visibility;\n }\n\n return this._unevaluatedLayout.getValue(name);\n }\n\n setLayoutProperty(name: string, value: any, options: StyleSetterOptions = {}) {\n if (value !== null && value !== undefined) {\n const key = `layers.${this.id}.layout.${name}`;\n if (this._validate(validateLayoutProperty, key, name, value, options)) {\n return;\n }\n }\n\n if (name === 'visibility') {\n this.visibility = value;\n return;\n }\n\n this._unevaluatedLayout.setValue(name, value);\n }\n\n getPaintProperty(name: string) {\n if (name.endsWith(TRANSITION_SUFFIX)) {\n return this._transitionablePaint.getTransition(name.slice(0, -TRANSITION_SUFFIX.length));\n } else {\n return this._transitionablePaint.getValue(name);\n }\n }\n\n setPaintProperty(name: string, value: unknown, options: StyleSetterOptions = {}) {\n if (value !== null && value !== undefined) {\n const key = `layers.${this.id}.paint.${name}`;\n if (this._validate(validatePaintProperty, key, name, value, options)) {\n return false;\n }\n }\n\n if (name.endsWith(TRANSITION_SUFFIX)) {\n this._transitionablePaint.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), (value as any) || undefined);\n return false;\n } else {\n const transitionable = this._transitionablePaint._values[name];\n const isCrossFadedProperty = transitionable.property.specification['property-type'] === 'cross-faded-data-driven';\n const wasDataDriven = transitionable.value.isDataDriven();\n const oldValue = transitionable.value;\n\n this._transitionablePaint.setValue(name, value);\n this._handleSpecialPaintPropertyUpdate(name);\n\n const newValue = this._transitionablePaint._values[name].value;\n const isDataDriven = newValue.isDataDriven();\n\n // if a cross-faded value is changed, we need to make sure the new icons get added to each tile's iconAtlas\n // so a call to _updateLayer is necessary, and we return true from this function so it gets called in\n // Style#setPaintProperty\n return isDataDriven || wasDataDriven || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue);\n }\n }\n\n _handleSpecialPaintPropertyUpdate(_: string) {\n // No-op; can be overridden by derived classes.\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleOverridablePaintPropertyUpdate(name: string, oldValue: PropertyValue, newValue: PropertyValue): boolean {\n // No-op; can be overridden by derived classes.\n return false;\n }\n\n isHidden(zoom: number) {\n if (this.minzoom && zoom < this.minzoom) return true;\n if (this.maxzoom && zoom >= this.maxzoom) return true;\n return this.visibility === 'none';\n }\n\n updateTransitions(parameters: TransitionParameters) {\n this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint);\n }\n\n hasTransition() {\n return this._transitioningPaint.hasTransition();\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array) {\n if (parameters.getCrossfadeParameters) {\n this._crossfadeParameters = parameters.getCrossfadeParameters();\n }\n\n if (this._unevaluatedLayout) {\n (this as any).layout = this._unevaluatedLayout.possiblyEvaluate(parameters, undefined, availableImages);\n }\n\n (this as any).paint = this._transitioningPaint.possiblyEvaluate(parameters, undefined, availableImages);\n }\n\n serialize(): LayerSpecification {\n const output: LayerSpecification = {\n 'id': this.id,\n 'type': this.type as LayerSpecification['type'],\n 'source': this.source,\n 'source-layer': this.sourceLayer,\n 'metadata': this.metadata,\n 'minzoom': this.minzoom,\n 'maxzoom': this.maxzoom,\n 'filter': this.filter as FilterSpecification,\n 'layout': this._unevaluatedLayout && this._unevaluatedLayout.serialize(),\n 'paint': this._transitionablePaint && this._transitionablePaint.serialize()\n };\n\n if (this.visibility) {\n output.layout = output.layout || {};\n output.layout.visibility = this.visibility;\n }\n\n return filterObject(output, (value, key) => {\n return value !== undefined &&\n !(key === 'layout' && !Object.keys(value).length) &&\n !(key === 'paint' && !Object.keys(value).length);\n });\n }\n\n _validate(validate: Function, key: string, name: string, value: unknown, options: StyleSetterOptions = {}) {\n if (options && options.validate === false) {\n return false;\n }\n return emitValidationErrors(this, validate.call(validateStyle, {\n key,\n layerType: this.type,\n objectKey: name,\n value,\n styleSpec,\n // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407\n style: {glyphs: true, sprite: true}\n }));\n }\n\n is3D() {\n return false;\n }\n\n isTileClipped() {\n return false;\n }\n\n hasOffscreenPass() {\n return false;\n }\n\n resize() {\n // noop\n }\n\n isStateDependent() {\n for (const property in (this as any).paint._values) {\n const value = (this as any).paint.get(property);\n if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {\n continue;\n }\n\n if ((value.value.kind === 'source' || value.value.kind === 'composite') &&\n value.value.isStateDependent) {\n return true;\n }\n }\n return false;\n }\n}\n","// Note: all \"sizes\" are measured in bytes\n\n/**\n * @internal\n * A view type size\n */\nconst viewTypes = {\n 'Int8': Int8Array,\n 'Uint8': Uint8Array,\n 'Int16': Int16Array,\n 'Uint16': Uint16Array,\n 'Int32': Int32Array,\n 'Uint32': Uint32Array,\n 'Float32': Float32Array\n};\n\n/**\n * @internal\n * A view type size\n */\nexport type ViewType = keyof typeof viewTypes;\n\n/** @internal */\nclass Struct {\n _pos1: number;\n _pos2: number;\n _pos4: number;\n _pos8: number;\n readonly _structArray: StructArray;\n\n // The following properties are defined on the prototype of sub classes.\n size: number;\n\n /**\n * @param structArray - The StructArray the struct is stored in\n * @param index - The index of the struct in the StructArray.\n */\n constructor(structArray: StructArray, index: number) {\n (this as any)._structArray = structArray;\n this._pos1 = index * this.size;\n this._pos2 = this._pos1 / 2;\n this._pos4 = this._pos1 / 4;\n this._pos8 = this._pos1 / 8;\n }\n}\n\nconst DEFAULT_CAPACITY = 128;\nconst RESIZE_MULTIPLIER = 5;\n\n/**\n * @internal\n * A struct array member\n */\nexport type StructArrayMember = {\n name: string;\n type: ViewType;\n components: number;\n offset: number;\n};\n\nexport type StructArrayLayout = {\n members: Array;\n size: number;\n alignment: number;\n};\n\n/**\n * An array that can be deserialized\n */\nexport type SerializedStructArray = {\n length: number;\n arrayBuffer: ArrayBuffer;\n};\n\n/**\n * @internal\n * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray`\n * making it behave like an array of typed structs.\n *\n * Conceptually, a StructArray is comprised of elements, i.e., instances of its\n * associated struct type. Each particular struct type, together with an\n * alignment size, determines the memory layout of a StructArray whose elements\n * are of that type. Thus, for each such layout that we need, we have\n * a corresponding StructArrayLayout class, inheriting from StructArray and\n * implementing `emplaceBack()` and `_refreshViews()`.\n *\n * In some cases, where we need to access particular elements of a StructArray,\n * we implement a more specific subclass that inherits from one of the\n * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured\n * object whose properties are proxies into the underlying memory space for the\n * i-th element. This affords the convenience of working with (seemingly) plain\n * Javascript objects without the overhead of serializing/deserializing them\n * into ArrayBuffers for efficient web worker transfer.\n */\nabstract class StructArray {\n capacity: number;\n length: number;\n isTransferred: boolean;\n arrayBuffer: ArrayBuffer;\n uint8: Uint8Array;\n\n // The following properties are defined on the prototype.\n members: Array;\n bytesPerElement: number;\n abstract emplaceBack(...v: number[]);\n abstract emplace(i: number, ...v: number[]);\n\n constructor() {\n this.isTransferred = false;\n this.capacity = -1;\n this.resize(0);\n }\n\n /**\n * Serialize a StructArray instance. Serializes both the raw data and the\n * metadata needed to reconstruct the StructArray base class during\n * deserialization.\n */\n static serialize(array: StructArray, transferables?: Array): SerializedStructArray {\n\n array._trim();\n\n if (transferables) {\n array.isTransferred = true;\n transferables.push(array.arrayBuffer);\n }\n\n return {\n length: array.length,\n arrayBuffer: array.arrayBuffer,\n };\n }\n\n static deserialize(input: SerializedStructArray) {\n const structArray = Object.create(this.prototype);\n structArray.arrayBuffer = input.arrayBuffer;\n structArray.length = input.length;\n structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement;\n structArray._refreshViews();\n return structArray;\n }\n\n /**\n * Resize the array to discard unused capacity.\n */\n _trim() {\n if (this.length !== this.capacity) {\n this.capacity = this.length;\n this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement);\n this._refreshViews();\n }\n }\n\n /**\n * Resets the length of the array to 0 without de-allocating capacity.\n */\n clear() {\n this.length = 0;\n }\n\n /**\n * Resize the array.\n * If `n` is greater than the current length then additional elements with undefined values are added.\n * If `n` is less than the current length then the array will be reduced to the first `n` elements.\n * @param n - The new size of the array.\n */\n resize(n: number) {\n this.reserve(n);\n this.length = n;\n }\n\n /**\n * Indicate a planned increase in size, so that any necessary allocation may\n * be done once, ahead of time.\n * @param n - The expected size of the array.\n */\n reserve(n: number) {\n if (n > this.capacity) {\n this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY);\n this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement);\n\n const oldUint8Array = this.uint8;\n this._refreshViews();\n if (oldUint8Array) this.uint8.set(oldUint8Array);\n }\n }\n\n /**\n * Create TypedArray views for the current ArrayBuffer.\n */\n _refreshViews() {\n throw new Error('_refreshViews() must be implemented by each concrete StructArray layout');\n }\n}\n\n/**\n * Given a list of member fields, create a full StructArrayLayout, in\n * particular calculating the correct byte offset for each field. This data\n * is used at build time to generate StructArrayLayout_*#emplaceBack() and\n * other accessors, and at runtime for binding vertex buffer attributes.\n */\nfunction createLayout(\n members: Array<{\n name: string;\n type: ViewType;\n readonly components?: number;\n }>,\n alignment: number = 1\n): StructArrayLayout {\n\n let offset = 0;\n let maxSize = 0;\n const layoutMembers = members.map((member) => {\n const typeSize = sizeOf(member.type);\n const memberOffset = offset = align(offset, Math.max(alignment, typeSize));\n const components = member.components || 1;\n\n maxSize = Math.max(maxSize, typeSize);\n offset += typeSize * components;\n\n return {\n name: member.name,\n type: member.type,\n components,\n offset: memberOffset,\n };\n });\n\n const size = align(offset, Math.max(maxSize, alignment));\n\n return {\n members: layoutMembers,\n size,\n alignment\n };\n}\n\nfunction sizeOf(type: ViewType): number {\n return viewTypes[type].BYTES_PER_ELEMENT;\n}\n\nfunction align(offset: number, size: number): number {\n return Math.ceil(offset / size) * size;\n}\n\nexport {StructArray, Struct, viewTypes, createLayout};\n","// This file is generated. Edit build/generate-struct-arrays.ts, then run `npm run codegen`.\n\nimport {Struct, StructArray} from '../util/struct_array';\nimport {register} from '../util/web_worker_transfer';\nimport Point from '@mapbox/point-geometry';\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n *\n */\nclass StructArrayLayout2i4 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1);\n }\n\n public emplace(i: number, v0: number, v1: number) {\n const o2 = i * 2;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n return i;\n }\n}\n\nStructArrayLayout2i4.prototype.bytesPerElement = 4;\nregister('StructArrayLayout2i4', StructArrayLayout2i4);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[3]\n *\n */\nclass StructArrayLayout3i6 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number) {\n const o2 = i * 3;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n return i;\n }\n}\n\nStructArrayLayout3i6.prototype.bytesPerElement = 6;\nregister('StructArrayLayout3i6', StructArrayLayout3i6);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[4]\n *\n */\nclass StructArrayLayout4i8 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number) {\n const o2 = i * 4;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n return i;\n }\n}\n\nStructArrayLayout4i8.prototype.bytesPerElement = 8;\nregister('StructArrayLayout4i8', StructArrayLayout4i8);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n * [4] - Int16[4]\n *\n */\nclass StructArrayLayout2i4i12 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number) {\n const o2 = i * 6;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n this.int16[o2 + 4] = v4;\n this.int16[o2 + 5] = v5;\n return i;\n }\n}\n\nStructArrayLayout2i4i12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout2i4i12', StructArrayLayout2i4i12);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n * [4] - Uint8[4]\n *\n */\nclass StructArrayLayout2i4ub8 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number) {\n const o2 = i * 4;\n const o1 = i * 8;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.uint8[o1 + 4] = v2;\n this.uint8[o1 + 5] = v3;\n this.uint8[o1 + 6] = v4;\n this.uint8[o1 + 7] = v5;\n return i;\n }\n}\n\nStructArrayLayout2i4ub8.prototype.bytesPerElement = 8;\nregister('StructArrayLayout2i4ub8', StructArrayLayout2i4ub8);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[2]\n *\n */\nclass StructArrayLayout2f8 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1);\n }\n\n public emplace(i: number, v0: number, v1: number) {\n const o4 = i * 2;\n this.float32[o4 + 0] = v0;\n this.float32[o4 + 1] = v1;\n return i;\n }\n}\n\nStructArrayLayout2f8.prototype.bytesPerElement = 8;\nregister('StructArrayLayout2f8', StructArrayLayout2f8);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[10]\n *\n */\nclass StructArrayLayout10ui20 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number) {\n const o2 = i * 10;\n this.uint16[o2 + 0] = v0;\n this.uint16[o2 + 1] = v1;\n this.uint16[o2 + 2] = v2;\n this.uint16[o2 + 3] = v3;\n this.uint16[o2 + 4] = v4;\n this.uint16[o2 + 5] = v5;\n this.uint16[o2 + 6] = v6;\n this.uint16[o2 + 7] = v7;\n this.uint16[o2 + 8] = v8;\n this.uint16[o2 + 9] = v9;\n return i;\n }\n}\n\nStructArrayLayout10ui20.prototype.bytesPerElement = 20;\nregister('StructArrayLayout10ui20', StructArrayLayout10ui20);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[4]\n * [8] - Uint16[4]\n * [16] - Int16[4]\n *\n */\nclass StructArrayLayout4i4ui4i24 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number) {\n const o2 = i * 12;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n this.uint16[o2 + 4] = v4;\n this.uint16[o2 + 5] = v5;\n this.uint16[o2 + 6] = v6;\n this.uint16[o2 + 7] = v7;\n this.int16[o2 + 8] = v8;\n this.int16[o2 + 9] = v9;\n this.int16[o2 + 10] = v10;\n this.int16[o2 + 11] = v11;\n return i;\n }\n}\n\nStructArrayLayout4i4ui4i24.prototype.bytesPerElement = 24;\nregister('StructArrayLayout4i4ui4i24', StructArrayLayout4i4ui4i24);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[3]\n *\n */\nclass StructArrayLayout3f12 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number) {\n const o4 = i * 3;\n this.float32[o4 + 0] = v0;\n this.float32[o4 + 1] = v1;\n this.float32[o4 + 2] = v2;\n return i;\n }\n}\n\nStructArrayLayout3f12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout3f12', StructArrayLayout3f12);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint32[1]\n *\n */\nclass StructArrayLayout1ul4 extends StructArray {\n uint8: Uint8Array;\n uint32: Uint32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n public emplace(i: number, v0: number) {\n const o4 = i * 1;\n this.uint32[o4 + 0] = v0;\n return i;\n }\n}\n\nStructArrayLayout1ul4.prototype.bytesPerElement = 4;\nregister('StructArrayLayout1ul4', StructArrayLayout1ul4);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[6]\n * [12] - Uint32[1]\n * [16] - Uint16[2]\n *\n */\nclass StructArrayLayout6i1ul2ui20 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n uint32: Uint32Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number) {\n const o2 = i * 10;\n const o4 = i * 5;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n this.int16[o2 + 4] = v4;\n this.int16[o2 + 5] = v5;\n this.uint32[o4 + 3] = v6;\n this.uint16[o2 + 8] = v7;\n this.uint16[o2 + 9] = v8;\n return i;\n }\n}\n\nStructArrayLayout6i1ul2ui20.prototype.bytesPerElement = 20;\nregister('StructArrayLayout6i1ul2ui20', StructArrayLayout6i1ul2ui20);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n * [4] - Int16[2]\n * [8] - Int16[2]\n *\n */\nclass StructArrayLayout2i2i2i12 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number) {\n const o2 = i * 6;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n this.int16[o2 + 4] = v4;\n this.int16[o2 + 5] = v5;\n return i;\n }\n}\n\nStructArrayLayout2i2i2i12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout2i2i2i12', StructArrayLayout2i2i2i12);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[2]\n * [8] - Float32[1]\n * [12] - Int16[2]\n *\n */\nclass StructArrayLayout2f1f2i16 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number) {\n const o4 = i * 4;\n const o2 = i * 8;\n this.float32[o4 + 0] = v0;\n this.float32[o4 + 1] = v1;\n this.float32[o4 + 2] = v2;\n this.int16[o2 + 6] = v3;\n this.int16[o2 + 7] = v4;\n return i;\n }\n}\n\nStructArrayLayout2f1f2i16.prototype.bytesPerElement = 16;\nregister('StructArrayLayout2f1f2i16', StructArrayLayout2f1f2i16);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint8[2]\n * [4] - Float32[2]\n * [12] - Int16[2]\n *\n */\nclass StructArrayLayout2ub2f2i16 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number) {\n const o1 = i * 16;\n const o4 = i * 4;\n const o2 = i * 8;\n this.uint8[o1 + 0] = v0;\n this.uint8[o1 + 1] = v1;\n this.float32[o4 + 1] = v2;\n this.float32[o4 + 2] = v3;\n this.int16[o2 + 6] = v4;\n this.int16[o2 + 7] = v5;\n return i;\n }\n}\n\nStructArrayLayout2ub2f2i16.prototype.bytesPerElement = 16;\nregister('StructArrayLayout2ub2f2i16', StructArrayLayout2ub2f2i16);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[3]\n *\n */\nclass StructArrayLayout3ui6 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number) {\n const o2 = i * 3;\n this.uint16[o2 + 0] = v0;\n this.uint16[o2 + 1] = v1;\n this.uint16[o2 + 2] = v2;\n return i;\n }\n}\n\nStructArrayLayout3ui6.prototype.bytesPerElement = 6;\nregister('StructArrayLayout3ui6', StructArrayLayout3ui6);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n * [4] - Uint16[2]\n * [8] - Uint32[3]\n * [20] - Uint16[3]\n * [28] - Float32[2]\n * [36] - Uint8[3]\n * [40] - Uint32[1]\n * [44] - Int16[1]\n *\n */\nclass StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n uint16: Uint16Array;\n uint32: Uint32Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number) {\n const o2 = i * 24;\n const o4 = i * 12;\n const o1 = i * 48;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.uint16[o2 + 2] = v2;\n this.uint16[o2 + 3] = v3;\n this.uint32[o4 + 2] = v4;\n this.uint32[o4 + 3] = v5;\n this.uint32[o4 + 4] = v6;\n this.uint16[o2 + 10] = v7;\n this.uint16[o2 + 11] = v8;\n this.uint16[o2 + 12] = v9;\n this.float32[o4 + 7] = v10;\n this.float32[o4 + 8] = v11;\n this.uint8[o1 + 36] = v12;\n this.uint8[o1 + 37] = v13;\n this.uint8[o1 + 38] = v14;\n this.uint32[o4 + 10] = v15;\n this.int16[o2 + 22] = v16;\n return i;\n }\n}\n\nStructArrayLayout2i2ui3ul3ui2f3ub1ul1i48.prototype.bytesPerElement = 48;\nregister('StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48', StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[8]\n * [16] - Uint16[15]\n * [48] - Uint32[1]\n * [52] - Float32[2]\n * [60] - Uint16[2]\n *\n */\nclass StructArrayLayout8i15ui1ul2f2ui64 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n uint16: Uint16Array;\n uint32: Uint32Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number, v18: number, v19: number, v20: number, v21: number, v22: number, v23: number, v24: number, v25: number, v26: number, v27: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number, v18: number, v19: number, v20: number, v21: number, v22: number, v23: number, v24: number, v25: number, v26: number, v27: number) {\n const o2 = i * 32;\n const o4 = i * 16;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n this.int16[o2 + 4] = v4;\n this.int16[o2 + 5] = v5;\n this.int16[o2 + 6] = v6;\n this.int16[o2 + 7] = v7;\n this.uint16[o2 + 8] = v8;\n this.uint16[o2 + 9] = v9;\n this.uint16[o2 + 10] = v10;\n this.uint16[o2 + 11] = v11;\n this.uint16[o2 + 12] = v12;\n this.uint16[o2 + 13] = v13;\n this.uint16[o2 + 14] = v14;\n this.uint16[o2 + 15] = v15;\n this.uint16[o2 + 16] = v16;\n this.uint16[o2 + 17] = v17;\n this.uint16[o2 + 18] = v18;\n this.uint16[o2 + 19] = v19;\n this.uint16[o2 + 20] = v20;\n this.uint16[o2 + 21] = v21;\n this.uint16[o2 + 22] = v22;\n this.uint32[o4 + 12] = v23;\n this.float32[o4 + 13] = v24;\n this.float32[o4 + 14] = v25;\n this.uint16[o2 + 30] = v26;\n this.uint16[o2 + 31] = v27;\n return i;\n }\n}\n\nStructArrayLayout8i15ui1ul2f2ui64.prototype.bytesPerElement = 64;\nregister('StructArrayLayout8i15ui1ul2f2ui64', StructArrayLayout8i15ui1ul2f2ui64);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[1]\n *\n */\nclass StructArrayLayout1f4 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n public emplace(i: number, v0: number) {\n const o4 = i * 1;\n this.float32[o4 + 0] = v0;\n return i;\n }\n}\n\nStructArrayLayout1f4.prototype.bytesPerElement = 4;\nregister('StructArrayLayout1f4', StructArrayLayout1f4);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[1]\n * [4] - Float32[2]\n *\n */\nclass StructArrayLayout1ui2f12 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number) {\n const o2 = i * 6;\n const o4 = i * 3;\n this.uint16[o2 + 0] = v0;\n this.float32[o4 + 1] = v1;\n this.float32[o4 + 2] = v2;\n return i;\n }\n}\n\nStructArrayLayout1ui2f12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout1ui2f12', StructArrayLayout1ui2f12);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint32[1]\n * [4] - Uint16[2]\n *\n */\nclass StructArrayLayout1ul2ui8 extends StructArray {\n uint8: Uint8Array;\n uint32: Uint32Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number) {\n const o4 = i * 2;\n const o2 = i * 4;\n this.uint32[o4 + 0] = v0;\n this.uint16[o2 + 2] = v1;\n this.uint16[o2 + 3] = v2;\n return i;\n }\n}\n\nStructArrayLayout1ul2ui8.prototype.bytesPerElement = 8;\nregister('StructArrayLayout1ul2ui8', StructArrayLayout1ul2ui8);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[2]\n *\n */\nclass StructArrayLayout2ui4 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1);\n }\n\n public emplace(i: number, v0: number, v1: number) {\n const o2 = i * 2;\n this.uint16[o2 + 0] = v0;\n this.uint16[o2 + 1] = v1;\n return i;\n }\n}\n\nStructArrayLayout2ui4.prototype.bytesPerElement = 4;\nregister('StructArrayLayout2ui4', StructArrayLayout2ui4);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[1]\n *\n */\nclass StructArrayLayout1ui2 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n public emplace(i: number, v0: number) {\n const o2 = i * 1;\n this.uint16[o2 + 0] = v0;\n return i;\n }\n}\n\nStructArrayLayout1ui2.prototype.bytesPerElement = 2;\nregister('StructArrayLayout1ui2', StructArrayLayout1ui2);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[4]\n *\n */\nclass StructArrayLayout4f16 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n public emplaceBack(v0: number, v1: number, v2: number, v3: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3);\n }\n\n public emplace(i: number, v0: number, v1: number, v2: number, v3: number) {\n const o4 = i * 4;\n this.float32[o4 + 0] = v0;\n this.float32[o4 + 1] = v1;\n this.float32[o4 + 2] = v2;\n this.float32[o4 + 3] = v3;\n return i;\n }\n}\n\nStructArrayLayout4f16.prototype.bytesPerElement = 16;\nregister('StructArrayLayout4f16', StructArrayLayout4f16);\n\n/** @internal */\nclass CollisionBoxStruct extends Struct {\n _structArray: CollisionBoxArray;\n get anchorPointX() { return this._structArray.int16[this._pos2 + 0]; }\n get anchorPointY() { return this._structArray.int16[this._pos2 + 1]; }\n get x1() { return this._structArray.int16[this._pos2 + 2]; }\n get y1() { return this._structArray.int16[this._pos2 + 3]; }\n get x2() { return this._structArray.int16[this._pos2 + 4]; }\n get y2() { return this._structArray.int16[this._pos2 + 5]; }\n get featureIndex() { return this._structArray.uint32[this._pos4 + 3]; }\n get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 8]; }\n get bucketIndex() { return this._structArray.uint16[this._pos2 + 9]; }\n get anchorPoint() { return new Point(this.anchorPointX, this.anchorPointY); }\n}\n\nCollisionBoxStruct.prototype.size = 20;\n\nexport type CollisionBox = CollisionBoxStruct;\n\n/** @internal */\nexport class CollisionBoxArray extends StructArrayLayout6i1ul2ui20 {\n /**\n * Return the CollisionBoxStruct at the given location in the array.\n * @param index The index of the element.\n */\n get(index: number): CollisionBoxStruct {\n return new CollisionBoxStruct(this, index);\n }\n}\n\nregister('CollisionBoxArray', CollisionBoxArray);\n\n/** @internal */\nclass PlacedSymbolStruct extends Struct {\n _structArray: PlacedSymbolArray;\n get anchorX() { return this._structArray.int16[this._pos2 + 0]; }\n get anchorY() { return this._structArray.int16[this._pos2 + 1]; }\n get glyphStartIndex() { return this._structArray.uint16[this._pos2 + 2]; }\n get numGlyphs() { return this._structArray.uint16[this._pos2 + 3]; }\n get vertexStartIndex() { return this._structArray.uint32[this._pos4 + 2]; }\n get lineStartIndex() { return this._structArray.uint32[this._pos4 + 3]; }\n get lineLength() { return this._structArray.uint32[this._pos4 + 4]; }\n get segment() { return this._structArray.uint16[this._pos2 + 10]; }\n get lowerSize() { return this._structArray.uint16[this._pos2 + 11]; }\n get upperSize() { return this._structArray.uint16[this._pos2 + 12]; }\n get lineOffsetX() { return this._structArray.float32[this._pos4 + 7]; }\n get lineOffsetY() { return this._structArray.float32[this._pos4 + 8]; }\n get writingMode() { return this._structArray.uint8[this._pos1 + 36]; }\n get placedOrientation() { return this._structArray.uint8[this._pos1 + 37]; }\n set placedOrientation(x: number) { this._structArray.uint8[this._pos1 + 37] = x; }\n get hidden() { return this._structArray.uint8[this._pos1 + 38]; }\n set hidden(x: number) { this._structArray.uint8[this._pos1 + 38] = x; }\n get crossTileID() { return this._structArray.uint32[this._pos4 + 10]; }\n set crossTileID(x: number) { this._structArray.uint32[this._pos4 + 10] = x; }\n get associatedIconIndex() { return this._structArray.int16[this._pos2 + 22]; }\n}\n\nPlacedSymbolStruct.prototype.size = 48;\n\nexport type PlacedSymbol = PlacedSymbolStruct;\n\n/** @internal */\nexport class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 {\n /**\n * Return the PlacedSymbolStruct at the given location in the array.\n * @param index The index of the element.\n */\n get(index: number): PlacedSymbolStruct {\n return new PlacedSymbolStruct(this, index);\n }\n}\n\nregister('PlacedSymbolArray', PlacedSymbolArray);\n\n/** @internal */\nclass SymbolInstanceStruct extends Struct {\n _structArray: SymbolInstanceArray;\n get anchorX() { return this._structArray.int16[this._pos2 + 0]; }\n get anchorY() { return this._structArray.int16[this._pos2 + 1]; }\n get rightJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 2]; }\n get centerJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 3]; }\n get leftJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 4]; }\n get verticalPlacedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 5]; }\n get placedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 6]; }\n get verticalPlacedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 7]; }\n get key() { return this._structArray.uint16[this._pos2 + 8]; }\n get textBoxStartIndex() { return this._structArray.uint16[this._pos2 + 9]; }\n get textBoxEndIndex() { return this._structArray.uint16[this._pos2 + 10]; }\n get verticalTextBoxStartIndex() { return this._structArray.uint16[this._pos2 + 11]; }\n get verticalTextBoxEndIndex() { return this._structArray.uint16[this._pos2 + 12]; }\n get iconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 13]; }\n get iconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 14]; }\n get verticalIconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 15]; }\n get verticalIconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 16]; }\n get featureIndex() { return this._structArray.uint16[this._pos2 + 17]; }\n get numHorizontalGlyphVertices() { return this._structArray.uint16[this._pos2 + 18]; }\n get numVerticalGlyphVertices() { return this._structArray.uint16[this._pos2 + 19]; }\n get numIconVertices() { return this._structArray.uint16[this._pos2 + 20]; }\n get numVerticalIconVertices() { return this._structArray.uint16[this._pos2 + 21]; }\n get useRuntimeCollisionCircles() { return this._structArray.uint16[this._pos2 + 22]; }\n get crossTileID() { return this._structArray.uint32[this._pos4 + 12]; }\n set crossTileID(x: number) { this._structArray.uint32[this._pos4 + 12] = x; }\n get textBoxScale() { return this._structArray.float32[this._pos4 + 13]; }\n get collisionCircleDiameter() { return this._structArray.float32[this._pos4 + 14]; }\n get textAnchorOffsetStartIndex() { return this._structArray.uint16[this._pos2 + 30]; }\n get textAnchorOffsetEndIndex() { return this._structArray.uint16[this._pos2 + 31]; }\n}\n\nSymbolInstanceStruct.prototype.size = 64;\n\nexport type SymbolInstance = SymbolInstanceStruct;\n\n/** @internal */\nexport class SymbolInstanceArray extends StructArrayLayout8i15ui1ul2f2ui64 {\n /**\n * Return the SymbolInstanceStruct at the given location in the array.\n * @param index The index of the element.\n */\n get(index: number): SymbolInstanceStruct {\n return new SymbolInstanceStruct(this, index);\n }\n}\n\nregister('SymbolInstanceArray', SymbolInstanceArray);\n\n/** @internal */\nexport class GlyphOffsetArray extends StructArrayLayout1f4 {\n getoffsetX(index: number) { return this.float32[index * 1 + 0]; }\n}\n\nregister('GlyphOffsetArray', GlyphOffsetArray);\n\n/** @internal */\nexport class SymbolLineVertexArray extends StructArrayLayout3i6 {\n getx(index: number) { return this.int16[index * 3 + 0]; }\n gety(index: number) { return this.int16[index * 3 + 1]; }\n gettileUnitDistanceFromAnchor(index: number) { return this.int16[index * 3 + 2]; }\n}\n\nregister('SymbolLineVertexArray', SymbolLineVertexArray);\n\n/** @internal */\nclass TextAnchorOffsetStruct extends Struct {\n _structArray: TextAnchorOffsetArray;\n get textAnchor() { return this._structArray.uint16[this._pos2 + 0]; }\n get textOffset0() { return this._structArray.float32[this._pos4 + 1]; }\n get textOffset1() { return this._structArray.float32[this._pos4 + 2]; }\n}\n\nTextAnchorOffsetStruct.prototype.size = 12;\n\nexport type TextAnchorOffset = TextAnchorOffsetStruct;\n\n/** @internal */\nexport class TextAnchorOffsetArray extends StructArrayLayout1ui2f12 {\n /**\n * Return the TextAnchorOffsetStruct at the given location in the array.\n * @param index The index of the element.\n */\n get(index: number): TextAnchorOffsetStruct {\n return new TextAnchorOffsetStruct(this, index);\n }\n}\n\nregister('TextAnchorOffsetArray', TextAnchorOffsetArray);\n\n/** @internal */\nclass FeatureIndexStruct extends Struct {\n _structArray: FeatureIndexArray;\n get featureIndex() { return this._structArray.uint32[this._pos4 + 0]; }\n get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 2]; }\n get bucketIndex() { return this._structArray.uint16[this._pos2 + 3]; }\n}\n\nFeatureIndexStruct.prototype.size = 8;\n\nexport type FeatureIndex = FeatureIndexStruct;\n\n/** @internal */\nexport class FeatureIndexArray extends StructArrayLayout1ul2ui8 {\n /**\n * Return the FeatureIndexStruct at the given location in the array.\n * @param index The index of the element.\n */\n get(index: number): FeatureIndexStruct {\n return new FeatureIndexStruct(this, index);\n }\n}\n\nregister('FeatureIndexArray', FeatureIndexArray);\n\nexport class PosArray extends StructArrayLayout2i4 {}\nexport class Pos3dArray extends StructArrayLayout3i6 {}\nexport class RasterBoundsArray extends StructArrayLayout4i8 {}\nexport class CircleLayoutArray extends StructArrayLayout2i4 {}\nexport class FillLayoutArray extends StructArrayLayout2i4 {}\nexport class FillExtrusionLayoutArray extends StructArrayLayout2i4i12 {}\nexport class HeatmapLayoutArray extends StructArrayLayout2i4 {}\nexport class LineLayoutArray extends StructArrayLayout2i4ub8 {}\nexport class LineExtLayoutArray extends StructArrayLayout2f8 {}\nexport class PatternLayoutArray extends StructArrayLayout10ui20 {}\nexport class SymbolLayoutArray extends StructArrayLayout4i4ui4i24 {}\nexport class SymbolDynamicLayoutArray extends StructArrayLayout3f12 {}\nexport class SymbolOpacityArray extends StructArrayLayout1ul4 {}\nexport class CollisionBoxLayoutArray extends StructArrayLayout2i2i2i12 {}\nexport class CollisionCircleLayoutArray extends StructArrayLayout2f1f2i16 {}\nexport class CollisionVertexArray extends StructArrayLayout2ub2f2i16 {}\nexport class QuadTriangleArray extends StructArrayLayout3ui6 {}\nexport class TriangleIndexArray extends StructArrayLayout3ui6 {}\nexport class LineIndexArray extends StructArrayLayout2ui4 {}\nexport class LineStripIndexArray extends StructArrayLayout1ui2 {}\nexport {\n StructArrayLayout2i4,\n StructArrayLayout3i6,\n StructArrayLayout4i8,\n StructArrayLayout2i4i12,\n StructArrayLayout2i4ub8,\n StructArrayLayout2f8,\n StructArrayLayout10ui20,\n StructArrayLayout4i4ui4i24,\n StructArrayLayout3f12,\n StructArrayLayout1ul4,\n StructArrayLayout6i1ul2ui20,\n StructArrayLayout2i2i2i12,\n StructArrayLayout2f1f2i16,\n StructArrayLayout2ub2f2i16,\n StructArrayLayout3ui6,\n StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48,\n StructArrayLayout8i15ui1ul2f2ui64,\n StructArrayLayout1f4,\n StructArrayLayout1ui2f12,\n StructArrayLayout1ul2ui8,\n StructArrayLayout2ui4,\n StructArrayLayout1ui2,\n StructArrayLayout4f16\n};\n","import {createLayout} from '../../util/struct_array';\n\nconst layout = createLayout([\n {name: 'a_pos', components: 2, type: 'Int16'}\n], 4);\n\nexport default layout;\nexport const {members, size, alignment} = layout;\n","import {warnOnce} from '../util/util';\n\nimport {register} from '../util/web_worker_transfer';\n\nimport type {VertexArrayObject} from '../render/vertex_array_object';\nimport type {StructArray} from '../util/struct_array';\n\n/**\n * @internal\n * A single segment of a vector\n */\nexport type Segment = {\n sortKey?: number;\n vertexOffset: number;\n primitiveOffset: number;\n vertexLength: number;\n primitiveLength: number;\n vaos: {[_: string]: VertexArrayObject};\n};\n\n/**\n * @internal\n * Used for calculations on vector segments\n */\nexport class SegmentVector {\n static MAX_VERTEX_ARRAY_LENGTH: number;\n segments: Array;\n\n constructor(segments: Array = []) {\n this.segments = segments;\n }\n\n prepareSegment(\n numVertices: number,\n layoutVertexArray: StructArray,\n indexArray: StructArray,\n sortKey?: number\n ): Segment {\n let segment: Segment = this.segments[this.segments.length - 1];\n if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}`);\n if (!segment || segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || segment.sortKey !== sortKey) {\n segment = ({\n vertexOffset: layoutVertexArray.length,\n primitiveOffset: indexArray.length,\n vertexLength: 0,\n primitiveLength: 0\n } as any);\n if (sortKey !== undefined) segment.sortKey = sortKey;\n this.segments.push(segment);\n }\n return segment;\n }\n\n get() {\n return this.segments;\n }\n\n destroy() {\n for (const segment of this.segments) {\n for (const k in segment.vaos) {\n segment.vaos[k].destroy();\n }\n }\n }\n\n static simpleSegment(\n vertexOffset: number,\n primitiveOffset: number,\n vertexLength: number,\n primitiveLength: number\n ): SegmentVector {\n return new SegmentVector([{\n vertexOffset,\n primitiveOffset,\n vertexLength,\n primitiveLength,\n vaos: {},\n sortKey: 0\n }]);\n }\n}\n\n/**\n * The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit\n * addressing of vertex buffers.\n */\nSegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1;\n\nregister('SegmentVector', SegmentVector);\n","import {clamp} from '../util/util';\n\n/**\n * Packs two numbers, interpreted as 8-bit unsigned integers, into a single\n * float. Unpack them in the shader using the `unpack_float()` function,\n * defined in _prelude.vertex.glsl\n */\nexport function packUint8ToFloat(a: number, b: number) {\n // coerce a and b to 8-bit ints\n a = clamp(Math.floor(a), 0, 255);\n b = clamp(Math.floor(b), 0, 255);\n return 256 * a + b;\n}\n","import {createLayout} from '../../util/struct_array';\n\nexport const patternAttributes = createLayout([\n // [tl.x, tl.y, br.x, br.y]\n {name: 'a_pattern_from', components: 4, type: 'Uint16'},\n {name: 'a_pattern_to', components: 4, type: 'Uint16'},\n {name: 'a_pixel_ratio_from', components: 1, type: 'Uint16'},\n {name: 'a_pixel_ratio_to', components: 1, type: 'Uint16'},\n]);\n","/**\n * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)\n * \n * @author Gary Court\n * @see http://github.com/garycourt/murmurhash-js\n * @author Austin Appleby\n * @see http://sites.google.com/site/murmurhash/\n * \n * @param {string} key ASCII only\n * @param {number} seed Positive integer only\n * @return {number} 32-bit positive integer hash \n */\n\nfunction murmurhash3_32_gc(key, seed) {\n\tvar remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i;\n\t\n\tremainder = key.length & 3; // key.length % 4\n\tbytes = key.length - remainder;\n\th1 = seed;\n\tc1 = 0xcc9e2d51;\n\tc2 = 0x1b873593;\n\ti = 0;\n\t\n\twhile (i < bytes) {\n\t \tk1 = \n\t \t ((key.charCodeAt(i) & 0xff)) |\n\t \t ((key.charCodeAt(++i) & 0xff) << 8) |\n\t \t ((key.charCodeAt(++i) & 0xff) << 16) |\n\t \t ((key.charCodeAt(++i) & 0xff) << 24);\n\t\t++i;\n\t\t\n\t\tk1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;\n\n\t\th1 ^= k1;\n h1 = (h1 << 13) | (h1 >>> 19);\n\t\th1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;\n\t\th1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));\n\t}\n\t\n\tk1 = 0;\n\t\n\tswitch (remainder) {\n\t\tcase 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;\n\t\tcase 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;\n\t\tcase 1: k1 ^= (key.charCodeAt(i) & 0xff);\n\t\t\n\t\tk1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;\n\t\th1 ^= k1;\n\t}\n\t\n\th1 ^= key.length;\n\n\th1 ^= h1 >>> 16;\n\th1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;\n\th1 ^= h1 >>> 13;\n\th1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;\n\th1 ^= h1 >>> 16;\n\n\treturn h1 >>> 0;\n}\n\nif(typeof module !== \"undefined\") {\n module.exports = murmurhash3_32_gc\n}","/**\n * JS Implementation of MurmurHash2\n * \n * @author Gary Court\n * @see http://github.com/garycourt/murmurhash-js\n * @author Austin Appleby\n * @see http://sites.google.com/site/murmurhash/\n * \n * @param {string} str ASCII only\n * @param {number} seed Positive integer only\n * @return {number} 32-bit positive integer hash\n */\n\nfunction murmurhash2_32_gc(str, seed) {\n var\n l = str.length,\n h = seed ^ l,\n i = 0,\n k;\n \n while (l >= 4) {\n \tk = \n \t ((str.charCodeAt(i) & 0xff)) |\n \t ((str.charCodeAt(++i) & 0xff) << 8) |\n \t ((str.charCodeAt(++i) & 0xff) << 16) |\n \t ((str.charCodeAt(++i) & 0xff) << 24);\n \n k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n k ^= k >>> 24;\n k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n\n\th = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k;\n\n l -= 4;\n ++i;\n }\n \n switch (l) {\n case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16;\n case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8;\n case 1: h ^= (str.charCodeAt(i) & 0xff);\n h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n }\n\n h ^= h >>> 13;\n h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n h ^= h >>> 15;\n\n return h >>> 0;\n}\n\nif(typeof module !== undefined) {\n module.exports = murmurhash2_32_gc\n}\n","var murmur3 = require(\"./murmurhash3_gc.js\")\nvar murmur2 = require(\"./murmurhash2_gc.js\")\n\nmodule.exports = murmur3\nmodule.exports.murmur3 = murmur3\nmodule.exports.murmur2 = murmur2\n","import murmur3 from 'murmurhash-js';\nimport {register} from '../util/web_worker_transfer';\n\ntype SerializedFeaturePositionMap = {\n ids: Float64Array;\n positions: Uint32Array;\n};\n\ntype FeaturePosition = {\n index: number;\n start: number;\n end: number;\n};\n\n// A transferable data structure that maps feature ids to their indices and buffer offsets\nexport class FeaturePositionMap {\n ids: Array;\n positions: Array;\n indexed: boolean;\n\n constructor() {\n this.ids = [];\n this.positions = [];\n this.indexed = false;\n }\n\n add(id: unknown, index: number, start: number, end: number) {\n this.ids.push(getNumericId(id));\n this.positions.push(index, start, end);\n }\n\n getPositions(id: unknown): Array {\n if (!this.indexed) throw new Error('Trying to get index, but feature positions are not indexed');\n\n const intId = getNumericId(id);\n\n // binary search for the first occurrence of id in this.ids;\n // relies on ids/positions being sorted by id, which happens in serialization\n let i = 0;\n let j = this.ids.length - 1;\n while (i < j) {\n const m = (i + j) >> 1;\n if (this.ids[m] >= intId) {\n j = m;\n } else {\n i = m + 1;\n }\n }\n const positions = [];\n while (this.ids[i] === intId) {\n const index = this.positions[3 * i];\n const start = this.positions[3 * i + 1];\n const end = this.positions[3 * i + 2];\n positions.push({index, start, end});\n i++;\n }\n return positions;\n }\n\n static serialize(map: FeaturePositionMap, transferables: Array): SerializedFeaturePositionMap {\n const ids = new Float64Array(map.ids);\n const positions = new Uint32Array(map.positions);\n\n sort(ids, positions, 0, ids.length - 1);\n\n if (transferables) {\n transferables.push(ids.buffer, positions.buffer);\n }\n\n return {ids, positions};\n }\n\n static deserialize(obj: SerializedFeaturePositionMap): FeaturePositionMap {\n const map = new FeaturePositionMap();\n // after transferring, we only use these arrays statically (no pushes),\n // so TypedArray vs Array distinction that flow points out doesn't matter\n map.ids = (obj.ids as any);\n map.positions = (obj.positions as any);\n map.indexed = true;\n return map;\n }\n}\n\nfunction getNumericId(value: unknown) {\n const numValue = +value;\n if (!isNaN(numValue) && numValue <= Number.MAX_SAFE_INTEGER) {\n return numValue;\n }\n return murmur3(String(value));\n}\n\n// custom quicksort that sorts ids, indices and offsets together (by ids)\n// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios\nfunction sort(ids, positions, left, right) {\n while (left < right) {\n const pivot = ids[(left + right) >> 1];\n let i = left - 1;\n let j = right + 1;\n\n while (true) {\n do i++; while (ids[i] < pivot);\n do j--; while (ids[j] > pivot);\n if (i >= j) break;\n swap(ids, i, j);\n swap(positions, 3 * i, 3 * j);\n swap(positions, 3 * i + 1, 3 * j + 1);\n swap(positions, 3 * i + 2, 3 * j + 2);\n }\n\n if (j - left < right - j) {\n sort(ids, positions, left, j);\n left = j + 1;\n } else {\n sort(ids, positions, j + 1, right);\n right = j;\n }\n }\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\nregister('FeaturePositionMap', FeaturePositionMap);\n","import {Color} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {Context} from '../gl/context';\nimport {mat4, vec2, vec3, vec4} from 'gl-matrix';\n\ntype $ObjMap any> = {\n [K in keyof T]: F extends (v: T[K]) => infer R ? R : never;\n};\n\nexport type UniformValues = $ObjMap(u: Uniform) => V>;\nexport type UniformLocations = {[_: string]: WebGLUniformLocation};\n\n/**\n * @internal\n * A base uniform abstract class\n */\nabstract class Uniform {\n gl: WebGLRenderingContext|WebGL2RenderingContext;\n location: WebGLUniformLocation;\n current: T;\n\n constructor(context: Context, location: WebGLUniformLocation) {\n this.gl = context.gl;\n this.location = location;\n }\n\n abstract set(v: T): void;\n}\n\nclass Uniform1i extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = 0;\n }\n\n set(v: number): void {\n if (this.current !== v) {\n this.current = v;\n this.gl.uniform1i(this.location, v);\n }\n }\n}\n\nclass Uniform1f extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = 0;\n }\n\n set(v: number): void {\n if (this.current !== v) {\n this.current = v;\n this.gl.uniform1f(this.location, v);\n }\n }\n}\n\nclass Uniform2f extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = [0, 0];\n }\n\n set(v: vec2): void {\n if (v[0] !== this.current[0] || v[1] !== this.current[1]) {\n this.current = v;\n this.gl.uniform2f(this.location, v[0], v[1]);\n }\n }\n}\n\nclass Uniform3f extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = [0, 0, 0];\n }\n\n set(v: vec3): void {\n if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) {\n this.current = v;\n this.gl.uniform3f(this.location, v[0], v[1], v[2]);\n }\n }\n}\n\nclass Uniform4f extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = [0, 0, 0, 0];\n }\n\n set(v: vec4): void {\n if (v[0] !== this.current[0] || v[1] !== this.current[1] ||\n v[2] !== this.current[2] || v[3] !== this.current[3]) {\n this.current = v;\n this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]);\n }\n }\n}\n\nclass UniformColor extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = Color.transparent;\n }\n\n set(v: Color): void {\n if (v.r !== this.current.r || v.g !== this.current.g ||\n v.b !== this.current.b || v.a !== this.current.a) {\n this.current = v;\n this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a);\n }\n }\n}\n\nconst emptyMat4 = new Float32Array(16) as mat4;\nclass UniformMatrix4f extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = emptyMat4;\n }\n\n set(v: mat4): void {\n // The vast majority of matrix comparisons that will trip this set\n // happen at i=12 or i=0, so we check those first to avoid lots of\n // unnecessary iteration:\n if (v[12] !== this.current[12] || v[0] !== this.current[0]) {\n this.current = v;\n this.gl.uniformMatrix4fv(this.location, false, v);\n return;\n }\n for (let i = 1; i < 16; i++) {\n if (v[i] !== this.current[i]) {\n this.current = v;\n this.gl.uniformMatrix4fv(this.location, false, v);\n break;\n }\n }\n }\n}\n\nexport {\n Uniform,\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n Uniform4f,\n UniformColor,\n UniformMatrix4f\n};\n\n/**\n * @internal\n * A uniform bindings\n */\nexport type UniformBindings = {[_: string]: Uniform};\n","import {packUint8ToFloat} from '../shaders/encode_attribute';\nimport {Color, supportsPropertyExpression} from '@maplibre/maplibre-gl-style-spec';\nimport {register} from '../util/web_worker_transfer';\nimport {PossiblyEvaluatedPropertyValue} from '../style/properties';\nimport {StructArrayLayout1f4, StructArrayLayout2f8, StructArrayLayout4f16, PatternLayoutArray} from './array_types.g';\nimport {clamp} from '../util/util';\nimport {patternAttributes} from './bucket/pattern_attributes';\nimport {EvaluationParameters} from '../style/evaluation_parameters';\nimport {FeaturePositionMap} from './feature_position_map';\nimport {Uniform, Uniform1f, UniformColor, Uniform4f} from '../render/uniform_binding';\n\nimport type {UniformLocations} from '../render/uniform_binding';\n\nimport type {CanonicalTileID} from '../source/tile_id';\nimport type {Context} from '../gl/context';\nimport type {TypedStyleLayer} from '../style/style_layer/typed_style_layer';\nimport type {CrossfadeParameters} from '../style/evaluation_parameters';\nimport type {StructArray, StructArrayMember} from '../util/struct_array';\nimport type {VertexBuffer} from '../gl/vertex_buffer';\nimport type {ImagePosition} from '../render/image_atlas';\nimport type {\n Feature,\n FeatureState,\n GlobalProperties,\n SourceExpression,\n CompositeExpression,\n FormattedSection\n} from '@maplibre/maplibre-gl-style-spec';\nimport type {FeatureStates} from '../source/source_state';\nimport type {VectorTileLayer} from '@mapbox/vector-tile';\n\nexport type BinderUniform = {\n name: string;\n property: string;\n binding: Uniform;\n};\n\nfunction packColor(color: Color): [number, number] {\n return [\n packUint8ToFloat(255 * color.r, 255 * color.g),\n packUint8ToFloat(255 * color.b, 255 * color.a)\n ];\n}\n\n/**\n * `Binder` is the interface definition for the strategies for constructing,\n * uploading, and binding paint property data as GLSL attributes. Most style-\n * spec properties have a 1:1 relationship to shader attribute/uniforms, but\n * some require multiple values per feature to be passed to the GPU, and in\n * those cases we bind multiple attributes/uniforms.\n *\n * It has three implementations, one for each of the three strategies we use:\n *\n * * For _constant_ properties -- those whose value is a constant, or the constant\n * result of evaluating a camera expression at a particular camera position -- we\n * don't need a vertex attribute buffer, and instead use a uniform.\n * * For data expressions, we use a vertex buffer with a single attribute value,\n * the evaluated result of the source function for the given feature.\n * * For composite expressions, we use a vertex buffer with two attributes: min and\n * max values covering the range of zooms at which we expect the tile to be\n * displayed. These values are calculated by evaluating the composite expression for\n * the given feature at strategically chosen zoom levels. In addition to this\n * attribute data, we also use a uniform value which the shader uses to interpolate\n * between the min and max value at the final displayed zoom level. The use of a\n * uniform allows us to cheaply update the value on every frame.\n *\n * Note that the shader source varies depending on whether we're using a uniform or\n * attribute. We dynamically compile shaders at runtime to accommodate this.\n */\ninterface AttributeBinder {\n populatePaintArray(\n length: number,\n feature: Feature,\n imagePositions: {[_: string]: ImagePosition},\n canonical?: CanonicalTileID,\n formattedSection?: FormattedSection\n ): void;\n updatePaintArray(\n start: number,\n length: number,\n feature: Feature,\n featureState: FeatureState,\n imagePositions: {[_: string]: ImagePosition}\n ): void;\n upload(a: Context): void;\n destroy(): void;\n}\n\ninterface UniformBinder {\n uniformNames: Array;\n setUniform(\n uniform: Uniform,\n globals: GlobalProperties,\n currentValue: PossiblyEvaluatedPropertyValue,\n uniformName: string\n ): void;\n getBinding(context: Context, location: WebGLUniformLocation, name: string): Partial>;\n}\n\nclass ConstantBinder implements UniformBinder {\n value: unknown;\n type: string;\n uniformNames: Array;\n\n constructor(value: unknown, names: Array, type: string) {\n this.value = value;\n this.uniformNames = names.map(name => `u_${name}`);\n this.type = type;\n }\n\n setUniform(\n uniform: Uniform,\n globals: GlobalProperties,\n currentValue: PossiblyEvaluatedPropertyValue\n ): void {\n uniform.set(currentValue.constantOr(this.value));\n }\n\n getBinding(context: Context, location: WebGLUniformLocation, _: string): Partial> {\n return (this.type === 'color') ?\n new UniformColor(context, location) :\n new Uniform1f(context, location);\n }\n}\n\nclass CrossFadedConstantBinder implements UniformBinder {\n uniformNames: Array;\n patternFrom: Array;\n patternTo: Array;\n pixelRatioFrom: number;\n pixelRatioTo: number;\n\n constructor(value: unknown, names: Array) {\n this.uniformNames = names.map(name => `u_${name}`);\n this.patternFrom = null;\n this.patternTo = null;\n this.pixelRatioFrom = 1.0;\n this.pixelRatioTo = 1.0;\n }\n\n setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition) {\n this.pixelRatioFrom = posFrom.pixelRatio;\n this.pixelRatioTo = posTo.pixelRatio;\n this.patternFrom = posFrom.tlbr;\n this.patternTo = posTo.tlbr;\n }\n\n setUniform(uniform: Uniform, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue, uniformName: string) {\n const pos =\n uniformName === 'u_pattern_to' ? this.patternTo :\n uniformName === 'u_pattern_from' ? this.patternFrom :\n uniformName === 'u_pixel_ratio_to' ? this.pixelRatioTo :\n uniformName === 'u_pixel_ratio_from' ? this.pixelRatioFrom : null;\n if (pos) uniform.set(pos);\n }\n\n getBinding(context: Context, location: WebGLUniformLocation, name: string): Partial> {\n return name.substr(0, 9) === 'u_pattern' ?\n new Uniform4f(context, location) :\n new Uniform1f(context, location);\n }\n}\n\nclass SourceExpressionBinder implements AttributeBinder {\n expression: SourceExpression;\n type: string;\n maxValue: number;\n\n paintVertexArray: StructArray;\n paintVertexAttributes: Array;\n paintVertexBuffer: VertexBuffer;\n\n constructor(expression: SourceExpression, names: Array, type: string, PaintVertexArray: {\n new (...args: any): StructArray;\n }) {\n this.expression = expression;\n this.type = type;\n this.maxValue = 0;\n this.paintVertexAttributes = names.map((name) => ({\n name: `a_${name}`,\n type: 'Float32',\n components: type === 'color' ? 2 : 1,\n offset: 0\n }));\n this.paintVertexArray = new PaintVertexArray();\n }\n\n populatePaintArray(newLength: number, feature: Feature, imagePositions: {[_: string]: ImagePosition}, canonical?: CanonicalTileID, formattedSection?: FormattedSection) {\n const start = this.paintVertexArray.length;\n const value = this.expression.evaluate(new EvaluationParameters(0), feature, {}, canonical, [], formattedSection);\n this.paintVertexArray.resize(newLength);\n this._setPaintValue(start, newLength, value);\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState) {\n const value = this.expression.evaluate({zoom: 0}, feature, featureState);\n this._setPaintValue(start, end, value);\n }\n\n _setPaintValue(start, end, value) {\n if (this.type === 'color') {\n const color = packColor(value);\n for (let i = start; i < end; i++) {\n this.paintVertexArray.emplace(i, color[0], color[1]);\n }\n } else {\n for (let i = start; i < end; i++) {\n this.paintVertexArray.emplace(i, value);\n }\n this.maxValue = Math.max(this.maxValue, Math.abs(value));\n }\n }\n\n upload(context: Context) {\n if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {\n if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) {\n this.paintVertexBuffer.updateData(this.paintVertexArray);\n } else {\n this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent);\n }\n }\n }\n\n destroy() {\n if (this.paintVertexBuffer) {\n this.paintVertexBuffer.destroy();\n }\n }\n}\n\nclass CompositeExpressionBinder implements AttributeBinder, UniformBinder {\n expression: CompositeExpression;\n uniformNames: Array;\n type: string;\n useIntegerZoom: boolean;\n zoom: number;\n maxValue: number;\n\n paintVertexArray: StructArray;\n paintVertexAttributes: Array;\n paintVertexBuffer: VertexBuffer;\n\n constructor(expression: CompositeExpression, names: Array, type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: {\n new (...args: any): StructArray;\n }) {\n this.expression = expression;\n this.uniformNames = names.map(name => `u_${name}_t`);\n this.type = type;\n this.useIntegerZoom = useIntegerZoom;\n this.zoom = zoom;\n this.maxValue = 0;\n this.paintVertexAttributes = names.map((name) => ({\n name: `a_${name}`,\n type: 'Float32',\n components: type === 'color' ? 4 : 2,\n offset: 0\n }));\n this.paintVertexArray = new PaintVertexArray();\n }\n\n populatePaintArray(newLength: number, feature: Feature, imagePositions: {[_: string]: ImagePosition}, canonical?: CanonicalTileID, formattedSection?: FormattedSection) {\n const min = this.expression.evaluate(new EvaluationParameters(this.zoom), feature, {}, canonical, [], formattedSection);\n const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1), feature, {}, canonical, [], formattedSection);\n const start = this.paintVertexArray.length;\n this.paintVertexArray.resize(newLength);\n this._setPaintValue(start, newLength, min, max);\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState) {\n const min = this.expression.evaluate({zoom: this.zoom}, feature, featureState);\n const max = this.expression.evaluate({zoom: this.zoom + 1}, feature, featureState);\n this._setPaintValue(start, end, min, max);\n }\n\n _setPaintValue(start, end, min, max) {\n if (this.type === 'color') {\n const minColor = packColor(min);\n const maxColor = packColor(max);\n for (let i = start; i < end; i++) {\n this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]);\n }\n } else {\n for (let i = start; i < end; i++) {\n this.paintVertexArray.emplace(i, min, max);\n }\n this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max));\n }\n }\n\n upload(context: Context) {\n if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {\n if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) {\n this.paintVertexBuffer.updateData(this.paintVertexArray);\n } else {\n this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent);\n }\n }\n }\n\n destroy() {\n if (this.paintVertexBuffer) {\n this.paintVertexBuffer.destroy();\n }\n }\n\n setUniform(uniform: Uniform, globals: GlobalProperties): void {\n const currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom;\n const factor = clamp(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1);\n uniform.set(factor);\n }\n\n getBinding(context: Context, location: WebGLUniformLocation, _: string): Uniform1f {\n return new Uniform1f(context, location);\n }\n}\n\nclass CrossFadedCompositeBinder implements AttributeBinder {\n expression: CompositeExpression;\n type: string;\n useIntegerZoom: boolean;\n zoom: number;\n layerId: string;\n\n zoomInPaintVertexArray: StructArray;\n zoomOutPaintVertexArray: StructArray;\n zoomInPaintVertexBuffer: VertexBuffer;\n zoomOutPaintVertexBuffer: VertexBuffer;\n paintVertexAttributes: Array;\n\n constructor(expression: CompositeExpression, type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: {\n new (...args: any): StructArray;\n }, layerId: string) {\n this.expression = expression;\n this.type = type;\n this.useIntegerZoom = useIntegerZoom;\n this.zoom = zoom;\n this.layerId = layerId;\n\n this.zoomInPaintVertexArray = new PaintVertexArray();\n this.zoomOutPaintVertexArray = new PaintVertexArray();\n }\n\n populatePaintArray(length: number, feature: Feature, imagePositions: {[_: string]: ImagePosition}) {\n const start = this.zoomInPaintVertexArray.length;\n this.zoomInPaintVertexArray.resize(length);\n this.zoomOutPaintVertexArray.resize(length);\n this._setPaintValues(start, length, feature.patterns && feature.patterns[this.layerId], imagePositions);\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState, imagePositions: {[_: string]: ImagePosition}) {\n this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions);\n }\n\n _setPaintValues(start, end, patterns, positions) {\n if (!positions || !patterns) return;\n\n const {min, mid, max} = patterns;\n const imageMin = positions[min];\n const imageMid = positions[mid];\n const imageMax = positions[max];\n if (!imageMin || !imageMid || !imageMax) return;\n\n // We populate two paint arrays because, for cross-faded properties, we don't know which direction\n // we're cross-fading to at layout time. In order to keep vertex attributes to a minimum and not pass\n // unnecessary vertex data to the shaders, we determine which to upload at draw time.\n for (let i = start; i < end; i++) {\n this.zoomInPaintVertexArray.emplace(i,\n imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1],\n imageMin.tl[0], imageMin.tl[1], imageMin.br[0], imageMin.br[1],\n imageMid.pixelRatio,\n imageMin.pixelRatio,\n );\n this.zoomOutPaintVertexArray.emplace(i,\n imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1],\n imageMax.tl[0], imageMax.tl[1], imageMax.br[0], imageMax.br[1],\n imageMid.pixelRatio,\n imageMax.pixelRatio,\n );\n }\n }\n\n upload(context: Context) {\n if (this.zoomInPaintVertexArray && this.zoomInPaintVertexArray.arrayBuffer && this.zoomOutPaintVertexArray && this.zoomOutPaintVertexArray.arrayBuffer) {\n this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, patternAttributes.members, this.expression.isStateDependent);\n this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, patternAttributes.members, this.expression.isStateDependent);\n }\n }\n\n destroy() {\n if (this.zoomOutPaintVertexBuffer) this.zoomOutPaintVertexBuffer.destroy();\n if (this.zoomInPaintVertexBuffer) this.zoomInPaintVertexBuffer.destroy();\n }\n}\n\n/**\n * @internal\n * ProgramConfiguration contains the logic for binding style layer properties and tile\n * layer feature data into GL program uniforms and vertex attributes.\n *\n * Non-data-driven property values are bound to shader uniforms. Data-driven property\n * values are bound to vertex attributes. In order to support a uniform GLSL syntax over\n * both, [Mapbox GL Shaders](https://github.com/mapbox/mapbox-gl-shaders) defines a `#pragma`\n * abstraction, which ProgramConfiguration is responsible for implementing. At runtime,\n * it examines the attributes of a particular layer, combines this with fixed knowledge\n * about how layers of the particular type are implemented, and determines which uniforms\n * and vertex attributes will be required. It can then substitute the appropriate text\n * into the shader source code, create and link a program, and bind the uniforms and\n * vertex attributes in preparation for drawing.\n *\n * When a vector tile is parsed, this same configuration information is used to\n * populate the attribute buffers needed for data-driven styling using the zoom\n * level and feature property data.\n */\nexport class ProgramConfiguration {\n binders: {[_: string]: AttributeBinder | UniformBinder};\n cacheKey: string;\n\n _buffers: Array;\n\n constructor(layer: TypedStyleLayer, zoom: number, filterProperties: (_: string) => boolean) {\n this.binders = {};\n this._buffers = [];\n\n const keys = [];\n\n for (const property in layer.paint._values) {\n if (!filterProperties(property)) continue;\n const value = (layer.paint as any).get(property);\n if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {\n continue;\n }\n const names = paintAttributeNames(property, layer.type);\n const expression = value.value;\n const type = value.property.specification.type;\n const useIntegerZoom = (value.property as any).useIntegerZoom;\n const propType = value.property.specification['property-type'];\n const isCrossFaded = propType === 'cross-faded' || propType === 'cross-faded-data-driven';\n\n if (expression.kind === 'constant') {\n this.binders[property] = isCrossFaded ?\n new CrossFadedConstantBinder(expression.value, names) :\n new ConstantBinder(expression.value, names, type);\n keys.push(`/u_${property}`);\n\n } else if (expression.kind === 'source' || isCrossFaded) {\n const StructArrayLayout = layoutType(property, type, 'source');\n this.binders[property] = isCrossFaded ?\n new CrossFadedCompositeBinder(expression as CompositeExpression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) :\n new SourceExpressionBinder(expression as SourceExpression, names, type, StructArrayLayout);\n keys.push(`/a_${property}`);\n\n } else {\n const StructArrayLayout = layoutType(property, type, 'composite');\n this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, zoom, StructArrayLayout);\n keys.push(`/z_${property}`);\n }\n }\n\n this.cacheKey = keys.sort().join('');\n }\n\n getMaxValue(property: string): number {\n const binder = this.binders[property];\n return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0;\n }\n\n populatePaintArrays(newLength: number, feature: Feature, imagePositions: {[_: string]: ImagePosition}, canonical?: CanonicalTileID, formattedSection?: FormattedSection) {\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder)\n (binder as AttributeBinder).populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection);\n }\n }\n setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition) {\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof CrossFadedConstantBinder)\n binder.setConstantPatternPositions(posTo, posFrom);\n }\n }\n\n updatePaintArrays(\n featureStates: FeatureStates,\n featureMap: FeaturePositionMap,\n vtLayer: VectorTileLayer,\n layer: TypedStyleLayer,\n imagePositions: {[_: string]: ImagePosition}\n ): boolean {\n let dirty: boolean = false;\n for (const id in featureStates) {\n const positions = featureMap.getPositions(id);\n\n for (const pos of positions) {\n const feature = vtLayer.feature(pos.index);\n\n for (const property in this.binders) {\n const binder = this.binders[property];\n if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ||\n binder instanceof CrossFadedCompositeBinder) && (binder as any).expression.isStateDependent === true) {\n //AHM: Remove after https://github.com/mapbox/mapbox-gl-js/issues/6255\n const value = (layer.paint as any).get(property);\n (binder as any).expression = value.value;\n (binder as AttributeBinder).updatePaintArray(pos.start, pos.end, feature, featureStates[id], imagePositions);\n dirty = true;\n }\n }\n }\n }\n return dirty;\n }\n\n defines(): Array {\n const result = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder) {\n result.push(...binder.uniformNames.map(name => `#define HAS_UNIFORM_${name}`));\n }\n }\n return result;\n }\n\n getBinderAttributes(): Array {\n const result = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) {\n for (let i = 0; i < binder.paintVertexAttributes.length; i++) {\n result.push(binder.paintVertexAttributes[i].name);\n }\n } else if (binder instanceof CrossFadedCompositeBinder) {\n for (let i = 0; i < patternAttributes.members.length; i++) {\n result.push(patternAttributes.members[i].name);\n }\n }\n }\n return result;\n }\n\n getBinderUniforms(): Array {\n const uniforms = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) {\n for (const uniformName of binder.uniformNames) {\n uniforms.push(uniformName);\n }\n }\n }\n return uniforms;\n }\n\n getPaintVertexBuffers(): Array {\n return this._buffers;\n }\n\n getUniforms(context: Context, locations: UniformLocations): Array {\n const uniforms = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) {\n for (const name of binder.uniformNames) {\n if (locations[name]) {\n const binding = binder.getBinding(context, locations[name], name);\n uniforms.push({name, property, binding});\n }\n }\n }\n }\n return uniforms;\n }\n\n setUniforms(\n context: Context,\n binderUniforms: Array,\n properties: any,\n globals: GlobalProperties\n ) {\n // Uniform state bindings are owned by the Program, but we set them\n // from within the ProgramConfiguration's binder members.\n for (const {name, property, binding} of binderUniforms) {\n (this.binders[property] as any).setUniform(binding, globals, properties.get(property), name);\n }\n }\n\n updatePaintBuffers(crossfade?: CrossfadeParameters) {\n this._buffers = [];\n\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (crossfade && binder instanceof CrossFadedCompositeBinder) {\n const patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer;\n if (patternVertexBuffer) this._buffers.push(patternVertexBuffer);\n\n } else if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) && binder.paintVertexBuffer) {\n this._buffers.push(binder.paintVertexBuffer);\n }\n }\n }\n\n upload(context: Context) {\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder)\n binder.upload(context);\n }\n this.updatePaintBuffers();\n }\n\n destroy() {\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder)\n binder.destroy();\n }\n }\n}\n\nexport class ProgramConfigurationSet {\n programConfigurations: {[_: string]: ProgramConfiguration};\n needsUpload: boolean;\n _featureMap: FeaturePositionMap;\n _bufferOffset: number;\n\n constructor(layers: ReadonlyArray, zoom: number, filterProperties: (_: string) => boolean = () => true) {\n this.programConfigurations = {};\n for (const layer of layers) {\n this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties);\n }\n this.needsUpload = false;\n this._featureMap = new FeaturePositionMap();\n this._bufferOffset = 0;\n }\n\n populatePaintArrays(length: number, feature: Feature, index: number, imagePositions: {[_: string]: ImagePosition}, canonical: CanonicalTileID, formattedSection?: FormattedSection) {\n for (const key in this.programConfigurations) {\n this.programConfigurations[key].populatePaintArrays(length, feature, imagePositions, canonical, formattedSection);\n }\n\n if (feature.id !== undefined) {\n this._featureMap.add(feature.id, index, this._bufferOffset, length);\n }\n this._bufferOffset = length;\n\n this.needsUpload = true;\n }\n\n updatePaintArrays(featureStates: FeatureStates, vtLayer: VectorTileLayer, layers: ReadonlyArray, imagePositions: {[_: string]: ImagePosition}) {\n for (const layer of layers) {\n this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, imagePositions) || this.needsUpload;\n }\n }\n\n get(layerId: string) {\n return this.programConfigurations[layerId];\n }\n\n upload(context: Context) {\n if (!this.needsUpload) return;\n for (const layerId in this.programConfigurations) {\n this.programConfigurations[layerId].upload(context);\n }\n this.needsUpload = false;\n }\n\n destroy() {\n for (const layerId in this.programConfigurations) {\n this.programConfigurations[layerId].destroy();\n }\n }\n}\n\nfunction paintAttributeNames(property, type) {\n const attributeNameExceptions = {\n 'text-opacity': ['opacity'],\n 'icon-opacity': ['opacity'],\n 'text-color': ['fill_color'],\n 'icon-color': ['fill_color'],\n 'text-halo-color': ['halo_color'],\n 'icon-halo-color': ['halo_color'],\n 'text-halo-blur': ['halo_blur'],\n 'icon-halo-blur': ['halo_blur'],\n 'text-halo-width': ['halo_width'],\n 'icon-halo-width': ['halo_width'],\n 'line-gap-width': ['gapwidth'],\n 'line-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'],\n 'fill-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'],\n 'fill-extrusion-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'],\n };\n\n return attributeNameExceptions[property] || [property.replace(`${type}-`, '').replace(/-/g, '_')];\n}\n\nfunction getLayoutException(property) {\n const propertyExceptions = {\n 'line-pattern': {\n 'source': PatternLayoutArray,\n 'composite': PatternLayoutArray\n },\n 'fill-pattern': {\n 'source': PatternLayoutArray,\n 'composite': PatternLayoutArray\n },\n 'fill-extrusion-pattern': {\n 'source': PatternLayoutArray,\n 'composite': PatternLayoutArray\n }\n };\n\n return propertyExceptions[property];\n}\n\nfunction layoutType(property, type, binderType) {\n const defaultLayouts = {\n 'color': {\n 'source': StructArrayLayout2f8,\n 'composite': StructArrayLayout4f16\n },\n 'number': {\n 'source': StructArrayLayout1f4,\n 'composite': StructArrayLayout2f8\n }\n };\n\n const layoutException = getLayoutException(property);\n return layoutException && layoutException[binderType] || defaultLayouts[type][binderType];\n}\n\nregister('ConstantBinder', ConstantBinder);\nregister('CrossFadedConstantBinder', CrossFadedConstantBinder);\nregister('SourceExpressionBinder', SourceExpressionBinder);\nregister('CrossFadedCompositeBinder', CrossFadedCompositeBinder);\nregister('CompositeExpressionBinder', CompositeExpressionBinder);\nregister('ProgramConfiguration', ProgramConfiguration, {omit: ['_buffers']});\nregister('ProgramConfigurationSet', ProgramConfigurationSet);\n","/**\n * The maximum value of a coordinate in the internal tile coordinate system. Coordinates of\n * all source features normalized to this extent upon load.\n *\n * The value is a consequence of the following:\n *\n * * Vertex buffer store positions as signed 16 bit integers.\n * * One bit is lost for signedness to support tile buffers.\n * * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int.\n * * One bit is lost to support features extending past the extent on the right edge of the tile.\n * * This leaves us with 2^13 = 8192\n */\nexport const EXTENT = 8192;\n","import {warnOnce, clamp} from '../util/util';\n\nimport {EXTENT} from './extent';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {VectorTileFeature} from '@mapbox/vector-tile';\n\n// These bounds define the minimum and maximum supported coordinate values.\n// While visible coordinates are within [0, EXTENT], tiles may theoretically\n// contain coordinates within [-Infinity, Infinity]. Our range is limited by the\n// number of bits used to represent the coordinate.\nconst BITS = 15;\nconst MAX = Math.pow(2, BITS - 1) - 1;\nconst MIN = -MAX - 1;\n\n/**\n * Loads a geometry from a VectorTileFeature and scales it to the common extent\n * used internally.\n * @param feature - the vector tile feature to load\n */\nexport function loadGeometry(feature: VectorTileFeature): Array> {\n const scale = EXTENT / feature.extent;\n const geometry = feature.loadGeometry();\n for (let r = 0; r < geometry.length; r++) {\n const ring = geometry[r];\n for (let p = 0; p < ring.length; p++) {\n const point = ring[p];\n // round here because mapbox-gl-native uses integers to represent\n // points and we need to do the same to avoid renering differences.\n const x = Math.round(point.x * scale);\n const y = Math.round(point.y * scale);\n\n point.x = clamp(x, MIN, MAX);\n point.y = clamp(y, MIN, MAX);\n\n if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) {\n // warn when exceeding allowed extent except for the 1-px-off case\n // https://github.com/mapbox/mapbox-gl-js/issues/8992\n warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size');\n }\n }\n }\n return geometry;\n}\n","import {loadGeometry} from './load_geometry';\nimport type Point from '@mapbox/point-geometry';\nimport type {VectorTileFeature} from '@mapbox/vector-tile';\nimport type {Feature} from '@maplibre/maplibre-gl-style-spec';\n\ntype EvaluationFeature = Feature & { geometry: Array> };\n/**\n * Construct a new feature based on a VectorTileFeature for expression evaluation, the geometry of which\n * will be loaded based on necessity.\n * @param feature - the feature to evaluate\n * @param needGeometry - if set to true this will load the geometry\n */\nexport function toEvaluationFeature(feature: VectorTileFeature, needGeometry: boolean): EvaluationFeature {\n return {type: feature.type,\n id: feature.id,\n properties: feature.properties,\n geometry: needGeometry ? loadGeometry(feature) : []};\n}\n","import {CircleLayoutArray} from '../array_types.g';\n\nimport {members as layoutAttributes} from './circle_attributes';\nimport {SegmentVector} from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {TriangleIndexArray} from '../index_array_type';\nimport {loadGeometry} from '../load_geometry';\nimport {toEvaluationFeature} from '../evaluation_feature';\nimport {EXTENT} from '../extent';\nimport {register} from '../../util/web_worker_transfer';\nimport {EvaluationParameters} from '../../style/evaluation_parameters';\n\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\nimport type {CircleStyleLayer} from '../../style/style_layer/circle_style_layer';\nimport type {HeatmapStyleLayer} from '../../style/style_layer/heatmap_style_layer';\nimport type {Context} from '../../gl/context';\nimport type {IndexBuffer} from '../../gl/index_buffer';\nimport type {VertexBuffer} from '../../gl/vertex_buffer';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\nimport type {VectorTileLayer} from '@mapbox/vector-tile';\n\nfunction addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) {\n layoutVertexArray.emplaceBack(\n (x * 2) + ((extrudeX + 1) / 2),\n (y * 2) + ((extrudeY + 1) / 2));\n}\n\n/**\n * @internal\n * Circles are represented by two triangles.\n *\n * Each corner has a pos that is the center of the circle and an extrusion\n * vector that is where it points.\n */\nexport class CircleBucket implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n layerIds: Array;\n layers: Array;\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n\n layoutVertexArray: CircleLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet;\n segments: SegmentVector;\n uploaded: boolean;\n\n constructor(options: BucketParameters) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n\n this.layoutVertexArray = new CircleLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.segments = new SegmentVector();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID) {\n const styleLayer = this.layers[0];\n const bucketFeatures: BucketFeature[] = [];\n let circleSortKey = null;\n let sortFeaturesByKey = false;\n\n // Heatmap layers are handled in this bucket and have no evaluated properties, so we check our access\n if (styleLayer.type === 'circle') {\n circleSortKey = (styleLayer as CircleStyleLayer).layout.get('circle-sort-key');\n sortFeaturesByKey = !circleSortKey.isConstant();\n }\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n const needGeometry = this.layers[0]._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) continue;\n\n const sortKey = sortFeaturesByKey ?\n circleSortKey.evaluate(evaluationFeature, {}, canonical) :\n undefined;\n\n const bucketFeature: BucketFeature = {\n id,\n properties: feature.properties,\n type: feature.type,\n sourceLayerIndex,\n index,\n geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),\n patterns: {},\n sortKey\n };\n\n bucketFeatures.push(bucketFeature);\n\n }\n\n if (sortFeaturesByKey) {\n bucketFeatures.sort((a, b) => a.sortKey - b.sortKey);\n }\n\n for (const bucketFeature of bucketFeatures) {\n const {geometry, index, sourceLayerIndex} = bucketFeature;\n const feature = features[index].feature;\n\n this.addFeature(bucketFeature, geometry, index, canonical);\n options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n }\n }\n\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);\n }\n\n isEmpty() {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending() {\n return !this.uploaded || this.programConfigurations.needsUpload;\n }\n\n upload(context: Context) {\n if (!this.uploaded) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n }\n this.programConfigurations.upload(context);\n this.uploaded = true;\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n }\n\n addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID) {\n for (const ring of geometry) {\n for (const point of ring) {\n const x = point.x;\n const y = point.y;\n\n // Do not include points that are outside the tile boundaries.\n if (x < 0 || x >= EXTENT || y < 0 || y >= EXTENT) continue;\n\n // this geometry will be of the Point type, and we'll derive\n // two triangles from it.\n //\n // ┌─────────┐\n // │ 3 2 │\n // │ │\n // │ 0 1 │\n // └─────────┘\n\n const segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray, feature.sortKey);\n const index = segment.vertexLength;\n\n addCircleVertex(this.layoutVertexArray, x, y, -1, -1);\n addCircleVertex(this.layoutVertexArray, x, y, 1, -1);\n addCircleVertex(this.layoutVertexArray, x, y, 1, 1);\n addCircleVertex(this.layoutVertexArray, x, y, -1, 1);\n\n this.indexArray.emplaceBack(index, index + 1, index + 2);\n this.indexArray.emplaceBack(index, index + 3, index + 2);\n\n segment.vertexLength += 4;\n segment.primitiveLength += 2;\n }\n }\n\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {}, canonical);\n }\n}\n\nregister('CircleBucket', CircleBucket, {omit: ['layers']});\n","import {isCounterClockwise} from './util';\n\nimport Point from '@mapbox/point-geometry';\n\nexport {polygonIntersectsBufferedPoint, polygonIntersectsMultiPolygon, polygonIntersectsBufferedMultiLine, polygonIntersectsPolygon, distToSegmentSquared, polygonIntersectsBox};\n\ntype Line = Array;\ntype MultiLine = Array;\ntype Ring = Array;\ntype Polygon = Array;\ntype MultiPolygon = Array;\n\nfunction polygonIntersectsPolygon(polygonA: Polygon, polygonB: Polygon) {\n for (let i = 0; i < polygonA.length; i++) {\n if (polygonContainsPoint(polygonB, polygonA[i])) return true;\n }\n\n for (let i = 0; i < polygonB.length; i++) {\n if (polygonContainsPoint(polygonA, polygonB[i])) return true;\n }\n\n if (lineIntersectsLine(polygonA, polygonB)) return true;\n\n return false;\n}\n\nfunction polygonIntersectsBufferedPoint(polygon: Polygon, point: Point, radius: number) {\n if (polygonContainsPoint(polygon, point)) return true;\n if (pointIntersectsBufferedLine(point, polygon, radius)) return true;\n return false;\n}\n\nfunction polygonIntersectsMultiPolygon(polygon: Polygon, multiPolygon: MultiPolygon) {\n\n if (polygon.length === 1) {\n return multiPolygonContainsPoint(multiPolygon, polygon[0]);\n }\n\n for (let m = 0; m < multiPolygon.length; m++) {\n const ring = multiPolygon[m];\n for (let n = 0; n < ring.length; n++) {\n if (polygonContainsPoint(polygon, ring[n])) return true;\n }\n }\n\n for (let i = 0; i < polygon.length; i++) {\n if (multiPolygonContainsPoint(multiPolygon, polygon[i])) return true;\n }\n\n for (let k = 0; k < multiPolygon.length; k++) {\n if (lineIntersectsLine(polygon, multiPolygon[k])) return true;\n }\n\n return false;\n}\n\nfunction polygonIntersectsBufferedMultiLine(polygon: Polygon, multiLine: MultiLine, radius: number) {\n for (let i = 0; i < multiLine.length; i++) {\n const line = multiLine[i];\n\n if (polygon.length >= 3) {\n for (let k = 0; k < line.length; k++) {\n if (polygonContainsPoint(polygon, line[k])) return true;\n }\n }\n\n if (lineIntersectsBufferedLine(polygon, line, radius)) return true;\n }\n return false;\n}\n\nfunction lineIntersectsBufferedLine(lineA: Line, lineB: Line, radius: number) {\n\n if (lineA.length > 1) {\n if (lineIntersectsLine(lineA, lineB)) return true;\n\n // Check whether any point in either line is within radius of the other line\n for (let j = 0; j < lineB.length; j++) {\n if (pointIntersectsBufferedLine(lineB[j], lineA, radius)) return true;\n }\n }\n\n for (let k = 0; k < lineA.length; k++) {\n if (pointIntersectsBufferedLine(lineA[k], lineB, radius)) return true;\n }\n\n return false;\n}\n\nfunction lineIntersectsLine(lineA: Line, lineB: Line) {\n if (lineA.length === 0 || lineB.length === 0) return false;\n for (let i = 0; i < lineA.length - 1; i++) {\n const a0 = lineA[i];\n const a1 = lineA[i + 1];\n for (let j = 0; j < lineB.length - 1; j++) {\n const b0 = lineB[j];\n const b1 = lineB[j + 1];\n if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) return true;\n }\n }\n return false;\n}\n\nfunction lineSegmentIntersectsLineSegment(a0: Point, a1: Point, b0: Point, b1: Point) {\n return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) &&\n isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1);\n}\n\nfunction pointIntersectsBufferedLine(p: Point, line: Line, radius: number) {\n const radiusSquared = radius * radius;\n\n if (line.length === 1) return p.distSqr(line[0]) < radiusSquared;\n\n for (let i = 1; i < line.length; i++) {\n // Find line segments that have a distance <= radius^2 to p\n // In that case, we treat the line as \"containing point p\".\n const v = line[i - 1], w = line[i];\n if (distToSegmentSquared(p, v, w) < radiusSquared) return true;\n }\n return false;\n}\n\n// Code from https://stackoverflow.com/a/1501725/331379.\nfunction distToSegmentSquared(p: Point, v: Point, w: Point) {\n const l2 = v.distSqr(w);\n if (l2 === 0) return p.distSqr(v);\n const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;\n if (t < 0) return p.distSqr(v);\n if (t > 1) return p.distSqr(w);\n return p.distSqr(w.sub(v)._mult(t)._add(v));\n}\n\n// point in polygon ray casting algorithm\nfunction multiPolygonContainsPoint(rings: Array, p: Point) {\n let c = false,\n ring, p1, p2;\n\n for (let k = 0; k < rings.length; k++) {\n ring = rings[k];\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n p1 = ring[i];\n p2 = ring[j];\n if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {\n c = !c;\n }\n }\n }\n return c;\n}\n\nfunction polygonContainsPoint(ring: Ring, p: Point) {\n let c = false;\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n const p1 = ring[i];\n const p2 = ring[j];\n if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {\n c = !c;\n }\n }\n return c;\n}\n\nfunction polygonIntersectsBox(ring: Ring, boxX1: number, boxY1: number, boxX2: number, boxY2: number) {\n for (const p of ring) {\n if (boxX1 <= p.x &&\n boxY1 <= p.y &&\n boxX2 >= p.x &&\n boxY2 >= p.y) return true;\n }\n\n const corners = [\n new Point(boxX1, boxY1),\n new Point(boxX1, boxY2),\n new Point(boxX2, boxY2),\n new Point(boxX2, boxY1)];\n\n if (ring.length > 2) {\n for (const corner of corners) {\n if (polygonContainsPoint(ring, corner)) return true;\n }\n }\n\n for (let i = 0; i < ring.length - 1; i++) {\n const p1 = ring[i];\n const p2 = ring[i + 1];\n if (edgeIntersectsBox(p1, p2, corners)) return true;\n }\n\n return false;\n}\n\nfunction edgeIntersectsBox(e1: Point, e2: Point, corners: Array) {\n const tl = corners[0];\n const br = corners[2];\n // the edge and box do not intersect in either the x or y dimensions\n if (((e1.x < tl.x) && (e2.x < tl.x)) ||\n ((e1.x > br.x) && (e2.x > br.x)) ||\n ((e1.y < tl.y) && (e2.y < tl.y)) ||\n ((e1.y > br.y) && (e2.y > br.y))) return false;\n\n // check if all corners of the box are on the same side of the edge\n const dir = isCounterClockwise(e1, e2, corners[0]);\n return dir !== isCounterClockwise(e1, e2, corners[1]) ||\n dir !== isCounterClockwise(e1, e2, corners[2]) ||\n dir !== isCounterClockwise(e1, e2, corners[3]);\n}\n","import Point from '@mapbox/point-geometry';\n\nimport type {PossiblyEvaluatedPropertyValue} from './properties';\nimport type {StyleLayer} from '../style/style_layer';\nimport type {CircleBucket} from '../data/bucket/circle_bucket';\nimport type {LineBucket} from '../data/bucket/line_bucket';\n\nexport function getMaximumPaintValue(\n property: string,\n layer: StyleLayer,\n bucket: CircleBucket | LineBucket\n): number {\n const value = ((layer.paint as any).get(property) as PossiblyEvaluatedPropertyValue).value;\n if (value.kind === 'constant') {\n return value.value;\n } else {\n return bucket.programConfigurations.get(layer.id).getMaxValue(property);\n }\n}\n\nexport function translateDistance(translate: [number, number]) {\n return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]);\n}\n\nexport function translate(queryGeometry: Array,\n translate: [number, number],\n translateAnchor: 'viewport' | 'map',\n bearing: number,\n pixelsToTileUnits: number) {\n if (!translate[0] && !translate[1]) {\n return queryGeometry;\n }\n const pt = Point.convert(translate)._mult(pixelsToTileUnits);\n\n if (translateAnchor === 'viewport') {\n pt._rotate(-bearing);\n }\n\n const translated = [];\n for (let i = 0; i < queryGeometry.length; i++) {\n const point = queryGeometry[i];\n translated.push(point.sub(pt));\n }\n return translated;\n}\n\nexport function offsetLine(rings: Array>, offset: number) {\n const newRings: Array> = [];\n for (let ringIndex = 0; ringIndex < rings.length; ringIndex++) {\n const ring = rings[ringIndex];\n const newRing: Array = [];\n for (let index = 0; index < ring.length; index++) {\n const a = ring[index - 1];\n const b = ring[index];\n const c = ring[index + 1];\n const aToB = index === 0 ? new Point(0, 0) : b.sub(a)._unit()._perp();\n const bToC = index === ring.length - 1 ? new Point(0, 0) : c.sub(b)._unit()._perp();\n const extrude = aToB._add(bToC)._unit();\n\n const cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y;\n if (cosHalfAngle !== 0) {\n extrude._mult(1 / cosHalfAngle);\n }\n\n newRing.push(extrude._mult(offset)._add(b));\n }\n newRings.push(newRing);\n }\n return newRings;\n}\n","// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty,\n PossiblyEvaluatedPropertyValue,\n CrossFaded\n} from '../properties';\n\nimport type {Color, Formatted, Padding, ResolvedImage, VariableAnchorOffsetCollection} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport type CircleLayoutProps = {\n \"circle-sort-key\": DataDrivenProperty,\n};\n\nexport type CircleLayoutPropsPossiblyEvaluated = {\n \"circle-sort-key\": PossiblyEvaluatedPropertyValue,\n};\n\nlet layout: Properties;\nconst getLayout = () => layout = layout || new Properties({\n \"circle-sort-key\": new DataDrivenProperty(styleSpec[\"layout_circle\"][\"circle-sort-key\"] as any as StylePropertySpecification),\n});\n\nexport type CirclePaintProps = {\n \"circle-radius\": DataDrivenProperty,\n \"circle-color\": DataDrivenProperty,\n \"circle-blur\": DataDrivenProperty,\n \"circle-opacity\": DataDrivenProperty,\n \"circle-translate\": DataConstantProperty<[number, number]>,\n \"circle-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"circle-pitch-scale\": DataConstantProperty<\"map\" | \"viewport\">,\n \"circle-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\">,\n \"circle-stroke-width\": DataDrivenProperty,\n \"circle-stroke-color\": DataDrivenProperty,\n \"circle-stroke-opacity\": DataDrivenProperty,\n};\n\nexport type CirclePaintPropsPossiblyEvaluated = {\n \"circle-radius\": PossiblyEvaluatedPropertyValue,\n \"circle-color\": PossiblyEvaluatedPropertyValue,\n \"circle-blur\": PossiblyEvaluatedPropertyValue,\n \"circle-opacity\": PossiblyEvaluatedPropertyValue,\n \"circle-translate\": [number, number],\n \"circle-translate-anchor\": \"map\" | \"viewport\",\n \"circle-pitch-scale\": \"map\" | \"viewport\",\n \"circle-pitch-alignment\": \"map\" | \"viewport\",\n \"circle-stroke-width\": PossiblyEvaluatedPropertyValue,\n \"circle-stroke-color\": PossiblyEvaluatedPropertyValue,\n \"circle-stroke-opacity\": PossiblyEvaluatedPropertyValue,\n};\n\nlet paint: Properties;\nconst getPaint = () => paint = paint || new Properties({\n \"circle-radius\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-radius\"] as any as StylePropertySpecification),\n \"circle-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-color\"] as any as StylePropertySpecification),\n \"circle-blur\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-blur\"] as any as StylePropertySpecification),\n \"circle-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-opacity\"] as any as StylePropertySpecification),\n \"circle-translate\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate\"] as any as StylePropertySpecification),\n \"circle-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate-anchor\"] as any as StylePropertySpecification),\n \"circle-pitch-scale\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-scale\"] as any as StylePropertySpecification),\n \"circle-pitch-alignment\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-alignment\"] as any as StylePropertySpecification),\n \"circle-stroke-width\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-width\"] as any as StylePropertySpecification),\n \"circle-stroke-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-color\"] as any as StylePropertySpecification),\n \"circle-stroke-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-opacity\"] as any as StylePropertySpecification),\n});\n\nexport default ({ get paint() { return getPaint() }, get layout() { return getLayout() } });","/**\n * Common utilities\n * @module glMatrix\n */\n// Configuration Constants\nexport var EPSILON = 0.000001;\nexport var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nexport var RANDOM = Math.random;\n/**\n * Sets the type of array used when creating new vectors and matrices\n *\n * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array\n */\n\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\nvar degree = Math.PI / 180;\n/**\n * Convert Degree To Radian\n *\n * @param {Number} a Angle in Degrees\n */\n\nexport function toRadian(a) {\n return a * degree;\n}\n/**\n * Tests whether or not the arguments have approximately the same value, within an absolute\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\n * than or equal to 1.0, and a relative tolerance is used for larger values)\n *\n * @param {Number} a The first number to test.\n * @param {Number} b The second number to test.\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\n */\n\nexport function equals(a, b) {\n return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));\n}\nif (!Math.hypot) Math.hypot = function () {\n var y = 0,\n i = arguments.length;\n\n while (i--) {\n y += arguments[i] * arguments[i];\n }\n\n return Math.sqrt(y);\n};","import * as glMatrix from \"./common.js\";\n/**\n * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(16);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\n\nexport function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\n\nexport function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a12 = a[6],\n a13 = a[7];\n var a23 = a[11];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);\n out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));\n out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);\n out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));\n out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));\n out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);\n out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));\n out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);\n out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);\n out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));\n out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);\n out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));\n out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));\n out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);\n out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));\n out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);\n return out;\n}\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n}\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15]; // Cache only the current line of the second matrix\n\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\n\nexport function translate(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n\n return out;\n}\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function rotate(out, a, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n var b00, b01, b02;\n var b10, b11, b12;\n var b20, b21, b22;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11]; // Construct the elements of the rotation matrix\n\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c; // Perform rotation-specific matrix multiplication\n\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateX(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateY(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateZ(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function fromRotation(out, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c; // Perform rotation-specific matrix multiplication\n\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromXRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromYRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromZRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\n\nexport function fromQuat2(out, a) {\n var translation = new glMatrix.ARRAY_TYPE(3);\n var bx = -a[0],\n by = -a[1],\n bz = -a[2],\n bw = a[3],\n ax = a[4],\n ay = a[5],\n az = a[6],\n aw = a[7];\n var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense\n\n if (magnitude > 0) {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n\n fromRotationTranslation(out, a, translation);\n return out;\n}\n/**\n * Returns the translation vector component of a transformation\n * matrix. If a matrix is built with fromRotationTranslation,\n * the returned vector will be the same as the translation vector\n * originally supplied.\n * @param {vec3} out Vector to receive translation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n return out;\n}\n/**\n * Returns the scaling factor component of a transformation\n * matrix. If a matrix is built with fromRotationTranslationScale\n * with a normalized Quaternion paramter, the returned vector will be\n * the same as the scaling vector\n * originally supplied.\n * @param {vec3} out Vector to receive scaling factor component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getScaling(out, mat) {\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out[0] = Math.hypot(m11, m12, m13);\n out[1] = Math.hypot(m21, m22, m23);\n out[2] = Math.hypot(m31, m32, m33);\n return out;\n}\n/**\n * Returns a quaternion representing the rotational component\n * of a transformation matrix. If a matrix is built with\n * fromRotationTranslation, the returned quaternion will be the\n * same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\n\nexport function getRotation(out, mat) {\n var scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n var is1 = 1 / scaling[0];\n var is2 = 1 / scaling[1];\n var is3 = 1 / scaling[2];\n var sm11 = mat[0] * is1;\n var sm12 = mat[1] * is2;\n var sm13 = mat[2] * is3;\n var sm21 = mat[4] * is1;\n var sm22 = mat[5] * is2;\n var sm23 = mat[6] * is3;\n var sm31 = mat[8] * is1;\n var sm32 = mat[9] * is2;\n var sm33 = mat[10] * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * mat4.translate(dest, origin);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n * mat4.translate(dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n var ox = o[0];\n var oy = o[1];\n var oz = o[2];\n var out0 = (1 - (yy + zz)) * sx;\n var out1 = (xy + wz) * sx;\n var out2 = (xz - wy) * sx;\n var out4 = (xy - wz) * sy;\n var out5 = (1 - (xx + zz)) * sy;\n var out6 = (yz + wx) * sy;\n var out8 = (xz + wy) * sz;\n var out9 = (yz - wx) * sz;\n var out10 = (1 - (xx + yy)) * sz;\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n return out;\n}\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function frustum(out, left, right, bottom, top, near, far) {\n var rl = 1 / (right - left);\n var tb = 1 / (top - bottom);\n var nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n\n return out;\n}\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\n\nexport var perspective = perspectiveNO;\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = far * nf;\n out[14] = far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -near;\n }\n\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = far * near / (near - far);\n out[15] = 0.0;\n return out;\n}\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\n\nexport var ortho = orthoNO;\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = near * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function lookAt(out, eye, center, up) {\n var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;\n var eyex = eye[0];\n var eyey = eye[1];\n var eyez = eye[2];\n var upx = up[0];\n var upy = up[1];\n var upz = up[2];\n var centerx = center[0];\n var centery = center[1];\n var centerz = center[2];\n\n if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {\n return identity(out);\n }\n\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n len = 1 / Math.hypot(z0, z1, z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.hypot(x0, x1, x2);\n\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n len = Math.hypot(y0, y1, y2);\n\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n return out;\n}\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function targetTo(out, eye, target, up) {\n var eyex = eye[0],\n eyey = eye[1],\n eyez = eye[2],\n upx = up[0],\n upy = up[1],\n upz = up[2];\n var z0 = eyex - target[0],\n z1 = eyey - target[1],\n z2 = eyez - target[2];\n var len = z0 * z0 + z1 * z1 + z2 * z2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n\n var x0 = upy * z2 - upz * z1,\n x1 = upz * z0 - upx * z2,\n x2 = upx * z1 - upy * z0;\n len = x0 * x0 + x1 * x1 + x2 * x2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \", \" + a[9] + \", \" + a[10] + \", \" + a[11] + \", \" + a[12] + \", \" + a[13] + \", \" + a[14] + \", \" + a[15] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);\n}\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7];\n var a8 = a[8],\n a9 = a[9],\n a10 = a[10],\n a11 = a[11];\n var a12 = a[12],\n a13 = a[13],\n a14 = a[14],\n a15 = a[15];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n var b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7];\n var b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11];\n var b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));\n}\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\n/**\n * 3 Dimensional Vector\n * @module vec3\n */\n\n/**\n * Creates a new, empty vec3\n *\n * @returns {vec3} a new 3D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(3);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec3 initialized with values from an existing vector\n *\n * @param {ReadonlyVec3} a vector to clone\n * @returns {vec3} a new 3D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Calculates the length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Creates a new vec3 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} a new 3D vector\n */\n\nexport function fromValues(x, y, z) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Copy the values from one vec3 to another\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the source vector\n * @returns {vec3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Set the components of a vec3 to the given values\n *\n * @param {vec3} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} out\n */\n\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Adds two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n return out;\n}\n/**\n * Multiplies two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n return out;\n}\n/**\n * Divides two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n return out;\n}\n/**\n * Math.ceil the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to ceil\n * @returns {vec3} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n return out;\n}\n/**\n * Math.floor the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to floor\n * @returns {vec3} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n return out;\n}\n/**\n * Returns the minimum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n return out;\n}\n/**\n * Returns the maximum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n return out;\n}\n/**\n * Math.round the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to round\n * @returns {vec3} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n return out;\n}\n/**\n * Scales a vec3 by a scalar number\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec3} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n return out;\n}\n/**\n * Adds two vec3's after scaling the second operand by a scalar value\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec3} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Calculates the squared euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Calculates the squared length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Negates the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to negate\n * @returns {vec3} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to invert\n * @returns {vec3} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n return out;\n}\n/**\n * Normalize a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to normalize\n * @returns {vec3} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var len = x * x + y * y + z * z;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n/**\n * Computes the cross product of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function cross(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2];\n var bx = b[0],\n by = b[1],\n bz = b[2];\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n/**\n * Performs a hermite interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function hermite(out, a, b, c, d, t) {\n var factorTimes2 = t * t;\n var factor1 = factorTimes2 * (2 * t - 3) + 1;\n var factor2 = factorTimes2 * (t - 2) + t;\n var factor3 = factorTimes2 * (t - 1);\n var factor4 = factorTimes2 * (3 - 2 * t);\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Performs a bezier interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function bezier(out, a, b, c, d, t) {\n var inverseFactor = 1 - t;\n var inverseFactorTimesTwo = inverseFactor * inverseFactor;\n var factorTimes2 = t * t;\n var factor1 = inverseFactorTimesTwo * inverseFactor;\n var factor2 = 3 * t * inverseFactorTimesTwo;\n var factor3 = 3 * factorTimes2 * inverseFactor;\n var factor4 = factorTimes2 * t;\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec3} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec3} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n var z = glMatrix.RANDOM() * 2.0 - 1.0;\n var zScale = Math.sqrt(1.0 - z * z) * scale;\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n/**\n * Transforms the vec3 with a mat4.\n * 4th vector component is implicitly '1'\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n/**\n * Transforms the vec3 with a mat3.\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n/**\n * Transforms the vec3 with a quat\n * Can also be used for dual quaternions. (Multiply it with the real part)\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec3} out\n */\n\nexport function transformQuat(out, a, q) {\n // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3];\n var x = a[0],\n y = a[1],\n z = a[2]; // var qvec = [qx, qy, qz];\n // var uv = vec3.cross([], qvec, a);\n\n var uvx = qy * z - qz * y,\n uvy = qz * x - qx * z,\n uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);\n\n var uuvx = qy * uvz - qz * uvy,\n uuvy = qz * uvx - qx * uvz,\n uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);\n\n var w2 = qw * 2;\n uvx *= w2;\n uvy *= w2;\n uvz *= w2; // vec3.scale(uuv, uuv, 2);\n\n uuvx *= 2;\n uuvy *= 2;\n uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));\n\n out[0] = x + uvx + uuvx;\n out[1] = y + uvy + uuvy;\n out[2] = z + uvz + uuvz;\n return out;\n}\n/**\n * Rotate a 3D vector around the x-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateX(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the y-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateY(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the z-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateZ(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2]; //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Get the angle between two 3D vectors\n * @param {ReadonlyVec3} a The first operand\n * @param {ReadonlyVec3} b The second operand\n * @returns {Number} The angle in radians\n */\n\nexport function angle(a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n bx = b[0],\n by = b[1],\n bz = b[2],\n mag1 = Math.sqrt(ax * ax + ay * ay + az * az),\n mag2 = Math.sqrt(bx * bx + by * by + bz * bz),\n mag = mag1 * mag2,\n cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\n * Set the components of a vec3 to zero\n *\n * @param {vec3} out the receiving vector\n * @returns {vec3} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec3} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));\n}\n/**\n * Alias for {@link vec3.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec3.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec3.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec3.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec3.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec3.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec3s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 3;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n\n return a;\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\n * 4 Dimensional Vector\n * @module vec4\n */\n\n/**\n * Creates a new, empty vec4\n *\n * @returns {vec4} a new 4D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec4 initialized with values from an existing vector\n *\n * @param {ReadonlyVec4} a vector to clone\n * @returns {vec4} a new 4D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Creates a new vec4 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} a new 4D vector\n */\n\nexport function fromValues(x, y, z, w) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Copy the values from one vec4 to another\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the source vector\n * @returns {vec4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to the given values\n *\n * @param {vec4} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} out\n */\n\nexport function set(out, x, y, z, w) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Adds two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n/**\n * Multiplies two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n out[3] = a[3] * b[3];\n return out;\n}\n/**\n * Divides two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n out[3] = a[3] / b[3];\n return out;\n}\n/**\n * Math.ceil the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to ceil\n * @returns {vec4} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n out[3] = Math.ceil(a[3]);\n return out;\n}\n/**\n * Math.floor the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to floor\n * @returns {vec4} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n out[3] = Math.floor(a[3]);\n return out;\n}\n/**\n * Returns the minimum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n out[3] = Math.min(a[3], b[3]);\n return out;\n}\n/**\n * Returns the maximum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n out[3] = Math.max(a[3], b[3]);\n return out;\n}\n/**\n * Math.round the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to round\n * @returns {vec4} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n out[3] = Math.round(a[3]);\n return out;\n}\n/**\n * Scales a vec4 by a scalar number\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec4} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n/**\n * Adds two vec4's after scaling the second operand by a scalar value\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec4} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Calculates the length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Negates the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to negate\n * @returns {vec4} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = -a[3];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to invert\n * @returns {vec4} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n out[3] = 1.0 / a[3];\n return out;\n}\n/**\n * Normalize a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to normalize\n * @returns {vec4} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n var len = x * x + y * y + z * z + w * w;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = x * len;\n out[1] = y * len;\n out[2] = z * len;\n out[3] = w * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n/**\n * Returns the cross-product of three vectors in a 4-dimensional space\n *\n * @param {ReadonlyVec4} result the receiving vector\n * @param {ReadonlyVec4} U the first vector\n * @param {ReadonlyVec4} V the second vector\n * @param {ReadonlyVec4} W the third vector\n * @returns {vec4} result\n */\n\nexport function cross(out, u, v, w) {\n var A = v[0] * w[1] - v[1] * w[0],\n B = v[0] * w[2] - v[2] * w[0],\n C = v[0] * w[3] - v[3] * w[0],\n D = v[1] * w[2] - v[2] * w[1],\n E = v[1] * w[3] - v[3] * w[1],\n F = v[2] * w[3] - v[3] * w[2];\n var G = u[0];\n var H = u[1];\n var I = u[2];\n var J = u[3];\n out[0] = H * F - I * E + J * D;\n out[1] = -(G * F) + I * C - J * B;\n out[2] = G * E - H * C + J * A;\n out[3] = -(G * D) + H * B - I * A;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec4} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n var aw = a[3];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n out[3] = aw + t * (b[3] - aw);\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec4} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec4} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a\n // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n // http://projecteuclid.org/euclid.aoms/1177692644;\n\n var v1, v2, v3, v4;\n var s1, s2;\n\n do {\n v1 = glMatrix.RANDOM() * 2 - 1;\n v2 = glMatrix.RANDOM() * 2 - 1;\n s1 = v1 * v1 + v2 * v2;\n } while (s1 >= 1);\n\n do {\n v3 = glMatrix.RANDOM() * 2 - 1;\n v4 = glMatrix.RANDOM() * 2 - 1;\n s2 = v3 * v3 + v4 * v4;\n } while (s2 >= 1);\n\n var d = Math.sqrt((1 - s1) / s2);\n out[0] = scale * v1;\n out[1] = scale * v2;\n out[2] = scale * v3 * d;\n out[3] = scale * v4 * d;\n return out;\n}\n/**\n * Transforms the vec4 with a mat4.\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec4} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n return out;\n}\n/**\n * Transforms the vec4 with a quat\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec4} out\n */\n\nexport function transformQuat(out, a, q) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3]; // calculate quat * vec\n\n var ix = qw * x + qy * z - qz * y;\n var iy = qw * y + qz * x - qx * z;\n var iz = qw * z + qx * y - qy * x;\n var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat\n\n out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to zero\n *\n * @param {vec4} out the receiving vector\n * @returns {vec4} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec4} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n/**\n * Alias for {@link vec4.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec4.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec4.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec4.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec4.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec4.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec4s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 4;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n vec[3] = a[i + 3];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n a[i + 3] = vec[3];\n }\n\n return a;\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\n * 2 Dimensional Vector\n * @module vec2\n */\n\n/**\n * Creates a new, empty vec2\n *\n * @returns {vec2} a new 2D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(2);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec2 initialized with values from an existing vector\n *\n * @param {ReadonlyVec2} a vector to clone\n * @returns {vec2} a new 2D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\n * Creates a new vec2 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @returns {vec2} a new 2D vector\n */\n\nexport function fromValues(x, y) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\n * Copy the values from one vec2 to another\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the source vector\n * @returns {vec2} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\n * Set the components of a vec2 to the given values\n *\n * @param {vec2} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @returns {vec2} out\n */\n\nexport function set(out, x, y) {\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\n * Adds two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n return out;\n}\n/**\n * Multiplies two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n return out;\n}\n/**\n * Divides two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n return out;\n}\n/**\n * Math.ceil the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to ceil\n * @returns {vec2} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n return out;\n}\n/**\n * Math.floor the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to floor\n * @returns {vec2} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n return out;\n}\n/**\n * Returns the minimum of two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n return out;\n}\n/**\n * Returns the maximum of two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n return out;\n}\n/**\n * Math.round the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to round\n * @returns {vec2} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n return out;\n}\n/**\n * Scales a vec2 by a scalar number\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec2} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n return out;\n}\n/**\n * Adds two vec2's after scaling the second operand by a scalar value\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec2} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec2's\n *\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0],\n y = b[1] - a[1];\n return Math.hypot(x, y);\n}\n/**\n * Calculates the squared euclidian distance between two vec2's\n *\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0],\n y = b[1] - a[1];\n return x * x + y * y;\n}\n/**\n * Calculates the length of a vec2\n *\n * @param {ReadonlyVec2} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0],\n y = a[1];\n return Math.hypot(x, y);\n}\n/**\n * Calculates the squared length of a vec2\n *\n * @param {ReadonlyVec2} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0],\n y = a[1];\n return x * x + y * y;\n}\n/**\n * Negates the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to negate\n * @returns {vec2} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to invert\n * @returns {vec2} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n return out;\n}\n/**\n * Normalize a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to normalize\n * @returns {vec2} out\n */\n\nexport function normalize(out, a) {\n var x = a[0],\n y = a[1];\n var len = x * x + y * y;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec2's\n *\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1];\n}\n/**\n * Computes the cross product of two vec2's\n * Note that the cross product must by definition produce a 3D vector\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec3} out\n */\n\nexport function cross(out, a, b) {\n var z = a[0] * b[1] - a[1] * b[0];\n out[0] = out[1] = 0;\n out[2] = z;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec2} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0],\n ay = a[1];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec2} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec2} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n out[0] = Math.cos(r) * scale;\n out[1] = Math.sin(r) * scale;\n return out;\n}\n/**\n * Transforms the vec2 with a mat2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat2} m matrix to transform with\n * @returns {vec2} out\n */\n\nexport function transformMat2(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n return out;\n}\n/**\n * Transforms the vec2 with a mat2d\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat2d} m matrix to transform with\n * @returns {vec2} out\n */\n\nexport function transformMat2d(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y + m[4];\n out[1] = m[1] * x + m[3] * y + m[5];\n return out;\n}\n/**\n * Transforms the vec2 with a mat3\n * 3rd vector component is implicitly '1'\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat3} m matrix to transform with\n * @returns {vec2} out\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[3] * y + m[6];\n out[1] = m[1] * x + m[4] * y + m[7];\n return out;\n}\n/**\n * Transforms the vec2 with a mat4\n * 3rd vector component is implicitly '0'\n * 4th vector component is implicitly '1'\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec2} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0];\n var y = a[1];\n out[0] = m[0] * x + m[4] * y + m[12];\n out[1] = m[1] * x + m[5] * y + m[13];\n return out;\n}\n/**\n * Rotate a 2D vector\n * @param {vec2} out The receiving vec2\n * @param {ReadonlyVec2} a The vec2 point to rotate\n * @param {ReadonlyVec2} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec2} out\n */\n\nexport function rotate(out, a, b, rad) {\n //Translate point to the origin\n var p0 = a[0] - b[0],\n p1 = a[1] - b[1],\n sinC = Math.sin(rad),\n cosC = Math.cos(rad); //perform rotation and translate to correct position\n\n out[0] = p0 * cosC - p1 * sinC + b[0];\n out[1] = p0 * sinC + p1 * cosC + b[1];\n return out;\n}\n/**\n * Get the angle between two 2D vectors\n * @param {ReadonlyVec2} a The first operand\n * @param {ReadonlyVec2} b The second operand\n * @returns {Number} The angle in radians\n */\n\nexport function angle(a, b) {\n var x1 = a[0],\n y1 = a[1],\n x2 = b[0],\n y2 = b[1],\n // mag is the product of the magnitudes of a and b\n mag = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2),\n // mag &&.. short circuits if mag == 0\n cosine = mag && (x1 * x2 + y1 * y2) / mag; // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1\n\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\n * Set the components of a vec2 to zero\n *\n * @param {vec2} out the receiving vector\n * @returns {vec2} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec2} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec2(\" + a[0] + \", \" + a[1] + \")\";\n}\n/**\n * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec2} a The first vector.\n * @param {ReadonlyVec2} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec2} a The first vector.\n * @param {ReadonlyVec2} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1];\n var b0 = b[0],\n b1 = b[1];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1));\n}\n/**\n * Alias for {@link vec2.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec2.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec2.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec2.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec2.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec2.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec2.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec2s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 2;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n }\n\n return a;\n };\n}();","import {StyleLayer} from '../style_layer';\n\nimport {CircleBucket} from '../../data/bucket/circle_bucket';\nimport {polygonIntersectsBufferedPoint} from '../../util/intersection_tests';\nimport {getMaximumPaintValue, translateDistance, translate} from '../query_utils';\nimport properties, {CircleLayoutPropsPossiblyEvaluated, CirclePaintPropsPossiblyEvaluated} from './circle_style_layer_properties.g';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties';\nimport {mat4, vec4} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\nimport type {FeatureState, LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Transform} from '../../geo/transform';\nimport type {Bucket, BucketParameters} from '../../data/bucket';\nimport type {CircleLayoutProps, CirclePaintProps} from './circle_style_layer_properties.g';\nimport type {VectorTileFeature} from '@mapbox/vector-tile';\n\n/**\n * A style layer that defines a circle\n */\nexport class CircleStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout;\n layout: PossiblyEvaluated;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n createBucket(parameters: BucketParameters) {\n return new CircleBucket(parameters);\n }\n\n queryRadius(bucket: Bucket): number {\n const circleBucket: CircleBucket = (bucket as any);\n return getMaximumPaintValue('circle-radius', this, circleBucket) +\n getMaximumPaintValue('circle-stroke-width', this, circleBucket) +\n translateDistance(this.paint.get('circle-translate'));\n }\n\n queryIntersectsFeature(\n queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number,\n pixelPosMatrix: mat4\n ): boolean {\n const translatedPolygon = translate(queryGeometry,\n this.paint.get('circle-translate'),\n this.paint.get('circle-translate-anchor'),\n transform.angle, pixelsToTileUnits);\n const radius = this.paint.get('circle-radius').evaluate(feature, featureState);\n const stroke = this.paint.get('circle-stroke-width').evaluate(feature, featureState);\n const size = radius + stroke;\n\n // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile\n // // Otherwise, compare geometry in the plane of the viewport\n // // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance\n // // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance\n const alignWithMap = this.paint.get('circle-pitch-alignment') === 'map';\n const transformedPolygon = alignWithMap ? translatedPolygon : projectQueryGeometry(translatedPolygon, pixelPosMatrix);\n const transformedSize = alignWithMap ? size * pixelsToTileUnits : size;\n\n for (const ring of geometry) {\n for (const point of ring) {\n\n const transformedPoint = alignWithMap ? point : projectPoint(point, pixelPosMatrix);\n\n let adjustedSize = transformedSize;\n const projectedCenter = vec4.transformMat4([] as any, [point.x, point.y, 0, 1], pixelPosMatrix);\n if (this.paint.get('circle-pitch-scale') === 'viewport' && this.paint.get('circle-pitch-alignment') === 'map') {\n adjustedSize *= projectedCenter[3] / transform.cameraToCenterDistance;\n } else if (this.paint.get('circle-pitch-scale') === 'map' && this.paint.get('circle-pitch-alignment') === 'viewport') {\n adjustedSize *= transform.cameraToCenterDistance / projectedCenter[3];\n }\n\n if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, adjustedSize)) return true;\n }\n }\n\n return false;\n }\n}\n\nfunction projectPoint(p: Point, pixelPosMatrix: mat4) {\n const point = vec4.transformMat4([] as any, [p.x, p.y, 0, 1], pixelPosMatrix);\n return new Point(point[0] / point[3], point[1] / point[3]);\n}\n\nfunction projectQueryGeometry(queryGeometry: Array, pixelPosMatrix: mat4) {\n return queryGeometry.map((p) => {\n return projectPoint(p, pixelPosMatrix);\n });\n}\n","import {CircleBucket} from './circle_bucket';\nimport {register} from '../../util/web_worker_transfer';\n\nimport type {HeatmapStyleLayer} from '../../style/style_layer/heatmap_style_layer';\n\nexport class HeatmapBucket extends CircleBucket {\n // Needed for flow to accept omit: ['layers'] below, due to\n // https://github.com/facebook/flow/issues/4262\n layers: Array;\n}\n\nregister('HeatmapBucket', HeatmapBucket, {omit: ['layers']});\n","// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty,\n PossiblyEvaluatedPropertyValue,\n CrossFaded\n} from '../properties';\n\nimport type {Color, Formatted, Padding, ResolvedImage, VariableAnchorOffsetCollection} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type HeatmapPaintProps = {\n \"heatmap-radius\": DataDrivenProperty,\n \"heatmap-weight\": DataDrivenProperty,\n \"heatmap-intensity\": DataConstantProperty,\n \"heatmap-color\": ColorRampProperty,\n \"heatmap-opacity\": DataConstantProperty,\n};\n\nexport type HeatmapPaintPropsPossiblyEvaluated = {\n \"heatmap-radius\": PossiblyEvaluatedPropertyValue,\n \"heatmap-weight\": PossiblyEvaluatedPropertyValue,\n \"heatmap-intensity\": number,\n \"heatmap-color\": ColorRampProperty,\n \"heatmap-opacity\": number,\n};\n\nlet paint: Properties;\nconst getPaint = () => paint = paint || new Properties({\n \"heatmap-radius\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-radius\"] as any as StylePropertySpecification),\n \"heatmap-weight\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-weight\"] as any as StylePropertySpecification),\n \"heatmap-intensity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-intensity\"] as any as StylePropertySpecification),\n \"heatmap-color\": new ColorRampProperty(styleSpec[\"paint_heatmap\"][\"heatmap-color\"] as any as StylePropertySpecification),\n \"heatmap-opacity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-opacity\"] as any as StylePropertySpecification),\n});\n\nexport default ({ get paint() { return getPaint() } });","import {register} from './web_worker_transfer';\n\nexport type Size = {\n width: number;\n height: number;\n};\n\ntype Point2D = {\n x: number;\n y: number;\n};\n\nfunction createImage(image: any, {\n width,\n height\n}: Size, channels: number, data?: Uint8Array | Uint8ClampedArray) {\n if (!data) {\n data = new Uint8Array(width * height * channels);\n } else if (data instanceof Uint8ClampedArray) {\n data = new Uint8Array(data.buffer);\n } else if (data.length !== width * height * channels) {\n throw new RangeError(`mismatched image size. expected: ${data.length} but got: ${width * height * channels}`);\n }\n image.width = width;\n image.height = height;\n image.data = data;\n return image;\n}\n\nfunction resizeImage(image: any, {\n width,\n height\n}: Size, channels: number) {\n if (width === image.width && height === image.height) {\n return;\n }\n\n const newImage = createImage({}, {width, height}, channels);\n\n copyImage(image, newImage, {x: 0, y: 0}, {x: 0, y: 0}, {\n width: Math.min(image.width, width),\n height: Math.min(image.height, height)\n }, channels);\n\n image.width = width;\n image.height = height;\n image.data = newImage.data;\n}\n\nfunction copyImage(srcImg: any, dstImg: any, srcPt: Point2D, dstPt: Point2D, size: Size, channels: number) {\n if (size.width === 0 || size.height === 0) {\n return dstImg;\n }\n\n if (size.width > srcImg.width ||\n size.height > srcImg.height ||\n srcPt.x > srcImg.width - size.width ||\n srcPt.y > srcImg.height - size.height) {\n throw new RangeError('out of range source coordinates for image copy');\n }\n\n if (size.width > dstImg.width ||\n size.height > dstImg.height ||\n dstPt.x > dstImg.width - size.width ||\n dstPt.y > dstImg.height - size.height) {\n throw new RangeError('out of range destination coordinates for image copy');\n }\n\n const srcData = srcImg.data;\n const dstData = dstImg.data;\n\n if (srcData === dstData) throw new Error('srcData equals dstData, so image is already copied');\n\n for (let y = 0; y < size.height; y++) {\n const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels;\n const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels;\n for (let i = 0; i < size.width * channels; i++) {\n dstData[dstOffset + i] = srcData[srcOffset + i];\n }\n }\n return dstImg;\n}\n\n/**\n * An image with alpha color value\n */\nexport class AlphaImage {\n width: number;\n height: number;\n data: Uint8Array;\n\n constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) {\n createImage(this, size, 1, data);\n }\n\n resize(size: Size) {\n resizeImage(this, size, 1);\n }\n\n clone() {\n return new AlphaImage({width: this.width, height: this.height}, new Uint8Array(this.data));\n }\n\n static copy(srcImg: AlphaImage, dstImg: AlphaImage, srcPt: Point2D, dstPt: Point2D, size: Size) {\n copyImage(srcImg, dstImg, srcPt, dstPt, size, 1);\n }\n}\n\n/**\n * An object to store image data not premultiplied, because ImageData is not premultiplied.\n * UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture.\n */\nexport class RGBAImage {\n width: number;\n height: number;\n\n /**\n * data must be a Uint8Array instead of Uint8ClampedArray because texImage2D does not support Uint8ClampedArray in all browsers.\n */\n data: Uint8Array;\n\n constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) {\n createImage(this, size, 4, data);\n }\n\n resize(size: Size) {\n resizeImage(this, size, 4);\n }\n\n replace(data: Uint8Array | Uint8ClampedArray, copy?: boolean) {\n if (copy) {\n this.data.set(data);\n } else if (data instanceof Uint8ClampedArray) {\n this.data = new Uint8Array(data.buffer);\n } else {\n this.data = data;\n }\n }\n\n clone() {\n return new RGBAImage({width: this.width, height: this.height}, new Uint8Array(this.data));\n }\n\n static copy(srcImg: RGBAImage | ImageData, dstImg: RGBAImage, srcPt: Point2D, dstPt: Point2D, size: Size) {\n copyImage(srcImg, dstImg, srcPt, dstPt, size, 4);\n }\n}\n\nregister('AlphaImage', AlphaImage);\nregister('RGBAImage', RGBAImage);\n","import {RGBAImage} from './image';\nimport {isPowerOfTwo} from './util';\n\nimport type {StylePropertyExpression} from '@maplibre/maplibre-gl-style-spec';\n\nexport type ColorRampParams = {\n expression: StylePropertyExpression;\n evaluationKey: string;\n resolution?: number;\n image?: RGBAImage;\n clips?: Array;\n};\n\n/**\n * Given an expression that should evaluate to a color ramp,\n * return a RGBA image representing that ramp expression.\n */\nexport function renderColorRamp(params: ColorRampParams): RGBAImage {\n const evaluationGlobals = {};\n const width = params.resolution || 256;\n const height = params.clips ? params.clips.length : 1;\n const image = params.image || new RGBAImage({width, height});\n\n if (!isPowerOfTwo(width)) throw new Error(`width is not a power of 2 - ${width}`);\n\n const renderPixel = (stride, index, progress) => {\n evaluationGlobals[params.evaluationKey] = progress;\n const pxColor = params.expression.evaluate(evaluationGlobals as any);\n // the colors are being unpremultiplied because Color uses\n // premultiplied values, and the Texture class expects unpremultiplied ones\n image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a);\n image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a);\n image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a);\n image.data[stride + index + 3] = Math.floor(pxColor.a * 255);\n };\n\n if (!params.clips) {\n for (let i = 0, j = 0; i < width; i++, j += 4) {\n const progress = i / (width - 1);\n\n renderPixel(0, j, progress);\n }\n } else {\n for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) {\n for (let i = 0, j = 0; i < width; i++, j += 4) {\n // Remap progress between clips\n const progress = i / (width - 1);\n const {start, end} = params.clips[clip];\n const evaluationProgress = start * (1 - progress) + end * progress;\n renderPixel(stride, j, evaluationProgress);\n }\n }\n }\n\n return image;\n}\n","import {StyleLayer} from '../style_layer';\n\nimport {HeatmapBucket} from '../../data/bucket/heatmap_bucket';\nimport {RGBAImage} from '../../util/image';\nimport properties, {HeatmapPaintPropsPossiblyEvaluated} from './heatmap_style_layer_properties.g';\nimport {renderColorRamp} from '../../util/color_ramp';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\n\nimport type {Texture} from '../../render/texture';\nimport type {Framebuffer} from '../../gl/framebuffer';\nimport type {HeatmapPaintProps} from './heatmap_style_layer_properties.g';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport const HEATMAP_FULL_RENDER_FBO_KEY = 'big-fb';\n\n/**\n * A style layer that defines a heatmap\n */\nexport class HeatmapStyleLayer extends StyleLayer {\n\n heatmapFbos: Map;\n colorRamp: RGBAImage;\n colorRampTexture: Texture;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n createBucket(options: any) {\n return new HeatmapBucket(options);\n }\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n\n this.heatmapFbos = new Map();\n // make sure color ramp texture is generated for default heatmap color too\n this._updateColorRamp();\n }\n\n _handleSpecialPaintPropertyUpdate(name: string) {\n if (name === 'heatmap-color') {\n this._updateColorRamp();\n }\n }\n\n _updateColorRamp() {\n const expression = this._transitionablePaint._values['heatmap-color'].value.expression;\n this.colorRamp = renderColorRamp({\n expression,\n evaluationKey: 'heatmapDensity',\n image: this.colorRamp\n });\n this.colorRampTexture = null;\n }\n\n resize() {\n if (this.heatmapFbos.has(HEATMAP_FULL_RENDER_FBO_KEY)) {\n this.heatmapFbos.delete(HEATMAP_FULL_RENDER_FBO_KEY);\n }\n }\n\n queryRadius(): number {\n return 0;\n }\n\n queryIntersectsFeature(): boolean {\n return false;\n }\n\n hasOffscreenPass() {\n return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none';\n }\n}\n","// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty,\n PossiblyEvaluatedPropertyValue,\n CrossFaded\n} from '../properties';\n\nimport type {Color, Formatted, Padding, ResolvedImage, VariableAnchorOffsetCollection} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type HillshadePaintProps = {\n \"hillshade-illumination-direction\": DataConstantProperty,\n \"hillshade-illumination-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"hillshade-exaggeration\": DataConstantProperty,\n \"hillshade-shadow-color\": DataConstantProperty,\n \"hillshade-highlight-color\": DataConstantProperty,\n \"hillshade-accent-color\": DataConstantProperty,\n};\n\nexport type HillshadePaintPropsPossiblyEvaluated = {\n \"hillshade-illumination-direction\": number,\n \"hillshade-illumination-anchor\": \"map\" | \"viewport\",\n \"hillshade-exaggeration\": number,\n \"hillshade-shadow-color\": Color,\n \"hillshade-highlight-color\": Color,\n \"hillshade-accent-color\": Color,\n};\n\nlet paint: Properties;\nconst getPaint = () => paint = paint || new Properties({\n \"hillshade-illumination-direction\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-direction\"] as any as StylePropertySpecification),\n \"hillshade-illumination-anchor\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-anchor\"] as any as StylePropertySpecification),\n \"hillshade-exaggeration\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-exaggeration\"] as any as StylePropertySpecification),\n \"hillshade-shadow-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-shadow-color\"] as any as StylePropertySpecification),\n \"hillshade-highlight-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-highlight-color\"] as any as StylePropertySpecification),\n \"hillshade-accent-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-accent-color\"] as any as StylePropertySpecification),\n});\n\nexport default ({ get paint() { return getPaint() } });","import {StyleLayer} from '../style_layer';\n\nimport properties, {HillshadePaintPropsPossiblyEvaluated} from './hillshade_style_layer_properties.g';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\n\nimport type {HillshadePaintProps} from './hillshade_style_layer_properties.g';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport class HillshadeStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n hasOffscreenPass() {\n return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none';\n }\n}\n","import {createLayout} from '../../util/struct_array';\n\nconst layout = createLayout([\n {name: 'a_pos', components: 2, type: 'Int16'}\n], 4);\n\nexport default layout;\nexport const {members, size, alignment} = layout;\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, 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 = Infinity;\n minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const 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 let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, 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 let 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 let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\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);\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 const 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 const 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 const 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 let 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 const 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 const 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 const 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 const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let 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) {\n let p = start;\n do {\n const 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, p.i, b.i);\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 let a = start;\n do {\n let 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 let 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 const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const 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 (let 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 const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const 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 let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let 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 const 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 const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\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 const 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 let 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 let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let 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 let 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 const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const 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 let 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 let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const 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 const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(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 const p = createNode(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 createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const 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 let sum = 0;\n for (let 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\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","import type {FillStyleLayer} from '../../style/style_layer/fill_style_layer';\nimport type {FillExtrusionStyleLayer} from '../../style/style_layer/fill_extrusion_style_layer';\nimport type {LineStyleLayer} from '../../style/style_layer/line_style_layer';\n\nimport type {\n BucketFeature,\n PopulateParameters\n} from '../bucket';\nimport {PossiblyEvaluated} from '../../style/properties';\n\ntype PatternStyleLayers = Array | Array | Array;\n\nexport function hasPattern(type: string, layers: PatternStyleLayers, options: PopulateParameters) {\n const patterns = options.patternDependencies;\n let hasPattern = false;\n\n for (const layer of layers) {\n const patternProperty = (layer.paint as PossiblyEvaluated).get(`${type}-pattern`);\n if (!patternProperty.isConstant()) {\n hasPattern = true;\n }\n\n const constantPattern = patternProperty.constantOr(null);\n if (constantPattern) {\n hasPattern = true;\n patterns[constantPattern.to] = true;\n patterns[constantPattern.from] = true;\n }\n }\n\n return hasPattern;\n}\n\nexport function addPatternDependencies(type: string, layers: PatternStyleLayers, patternFeature: BucketFeature, zoom: number, options: PopulateParameters) {\n const patterns = options.patternDependencies;\n for (const layer of layers) {\n const patternProperty = (layer.paint as PossiblyEvaluated).get(`${type}-pattern`);\n\n const patternPropertyValue = patternProperty.value;\n if (patternPropertyValue.kind !== 'constant') {\n let min = patternPropertyValue.evaluate({zoom: zoom - 1}, patternFeature, {}, options.availableImages);\n let mid = patternPropertyValue.evaluate({zoom}, patternFeature, {}, options.availableImages);\n let max = patternPropertyValue.evaluate({zoom: zoom + 1}, patternFeature, {}, options.availableImages);\n min = min && min.name ? min.name : min;\n mid = mid && mid.name ? mid.name : mid;\n max = max && max.name ? max.name : max;\n // add to patternDependencies\n patterns[min] = true;\n patterns[mid] = true;\n patterns[max] = true;\n\n // save for layout\n patternFeature.patterns[layer.id] = {min, mid, max};\n }\n }\n return patternFeature;\n}\n","import {FillLayoutArray} from '../array_types.g';\n\nimport {members as layoutAttributes} from './fill_attributes';\nimport {SegmentVector} from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {LineIndexArray, TriangleIndexArray} from '../index_array_type';\nimport earcut from 'earcut';\nimport {classifyRings} from '@maplibre/maplibre-gl-style-spec';\nconst EARCUT_MAX_RINGS = 500;\nimport {register} from '../../util/web_worker_transfer';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features';\nimport {loadGeometry} from '../load_geometry';\nimport {toEvaluationFeature} from '../evaluation_feature';\nimport {EvaluationParameters} from '../../style/evaluation_parameters';\n\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\nimport type {FillStyleLayer} from '../../style/style_layer/fill_style_layer';\nimport type {Context} from '../../gl/context';\nimport type {IndexBuffer} from '../../gl/index_buffer';\nimport type {VertexBuffer} from '../../gl/vertex_buffer';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\nimport type {VectorTileLayer} from '@mapbox/vector-tile';\n\nexport class FillBucket implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n layers: Array;\n layerIds: Array;\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n patternFeatures: Array;\n\n layoutVertexArray: FillLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n indexArray2: LineIndexArray;\n indexBuffer2: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet;\n segments: SegmentVector;\n segments2: SegmentVector;\n uploaded: boolean;\n\n constructor(options: BucketParameters) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n this.patternFeatures = [];\n\n this.layoutVertexArray = new FillLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.indexArray2 = new LineIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.segments = new SegmentVector();\n this.segments2 = new SegmentVector();\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID) {\n this.hasPattern = hasPattern('fill', this.layers, options);\n const fillSortKey = this.layers[0].layout.get('fill-sort-key');\n const sortFeaturesByKey = !fillSortKey.isConstant();\n const bucketFeatures: BucketFeature[] = [];\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n const needGeometry = this.layers[0]._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) continue;\n\n const sortKey = sortFeaturesByKey ?\n fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) :\n undefined;\n\n const bucketFeature: BucketFeature = {\n id,\n properties: feature.properties,\n type: feature.type,\n sourceLayerIndex,\n index,\n geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),\n patterns: {},\n sortKey\n };\n\n bucketFeatures.push(bucketFeature);\n }\n\n if (sortFeaturesByKey) {\n bucketFeatures.sort((a, b) => a.sortKey - b.sortKey);\n }\n\n for (const bucketFeature of bucketFeatures) {\n const {geometry, index, sourceLayerIndex} = bucketFeature;\n\n if (this.hasPattern) {\n const patternFeature = addPatternDependencies('fill', this.layers, bucketFeature, this.zoom, options);\n // pattern features are added only once the pattern is loaded into the image atlas\n // so are stored during populate until later updated with positions by tile worker in addFeatures\n this.patternFeatures.push(patternFeature);\n } else {\n this.addFeature(bucketFeature, geometry, index, canonical, {});\n }\n\n const feature = features[index].feature;\n options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n }\n }\n\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {\n [_: string]: ImagePosition;\n }) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: {\n [_: string]: ImagePosition;\n }) {\n for (const feature of this.patternFeatures) {\n this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions);\n }\n }\n\n isEmpty() {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending(): boolean {\n return !this.uploaded || this.programConfigurations.needsUpload;\n }\n upload(context: Context) {\n if (!this.uploaded) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n this.indexBuffer2 = context.createIndexBuffer(this.indexArray2);\n }\n this.programConfigurations.upload(context);\n this.uploaded = true;\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.indexBuffer2.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n this.segments2.destroy();\n }\n\n addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID, imagePositions: {\n [_: string]: ImagePosition;\n }) {\n for (const polygon of classifyRings(geometry, EARCUT_MAX_RINGS)) {\n let numVertices = 0;\n for (const ring of polygon) {\n numVertices += ring.length;\n }\n\n const triangleSegment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray);\n const triangleIndex = triangleSegment.vertexLength;\n\n const flattened = [];\n const holeIndices = [];\n\n for (const ring of polygon) {\n if (ring.length === 0) {\n continue;\n }\n\n if (ring !== polygon[0]) {\n holeIndices.push(flattened.length / 2);\n }\n\n const lineSegment = this.segments2.prepareSegment(ring.length, this.layoutVertexArray, this.indexArray2);\n const lineIndex = lineSegment.vertexLength;\n\n this.layoutVertexArray.emplaceBack(ring[0].x, ring[0].y);\n this.indexArray2.emplaceBack(lineIndex + ring.length - 1, lineIndex);\n flattened.push(ring[0].x);\n flattened.push(ring[0].y);\n\n for (let i = 1; i < ring.length; i++) {\n this.layoutVertexArray.emplaceBack(ring[i].x, ring[i].y);\n this.indexArray2.emplaceBack(lineIndex + i - 1, lineIndex + i);\n flattened.push(ring[i].x);\n flattened.push(ring[i].y);\n }\n\n lineSegment.vertexLength += ring.length;\n lineSegment.primitiveLength += ring.length;\n }\n\n const indices = earcut(flattened, holeIndices);\n\n for (let i = 0; i < indices.length; i += 3) {\n this.indexArray.emplaceBack(\n triangleIndex + indices[i],\n triangleIndex + indices[i + 1],\n triangleIndex + indices[i + 2]);\n }\n\n triangleSegment.vertexLength += numVertices;\n triangleSegment.primitiveLength += indices.length / 3;\n }\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical);\n }\n}\n\nregister('FillBucket', FillBucket, {omit: ['layers', 'patternFeatures']});\n","// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty,\n PossiblyEvaluatedPropertyValue,\n CrossFaded\n} from '../properties';\n\nimport type {Color, Formatted, Padding, ResolvedImage, VariableAnchorOffsetCollection} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport type FillLayoutProps = {\n \"fill-sort-key\": DataDrivenProperty,\n};\n\nexport type FillLayoutPropsPossiblyEvaluated = {\n \"fill-sort-key\": PossiblyEvaluatedPropertyValue,\n};\n\nlet layout: Properties;\nconst getLayout = () => layout = layout || new Properties({\n \"fill-sort-key\": new DataDrivenProperty(styleSpec[\"layout_fill\"][\"fill-sort-key\"] as any as StylePropertySpecification),\n});\n\nexport type FillPaintProps = {\n \"fill-antialias\": DataConstantProperty,\n \"fill-opacity\": DataDrivenProperty,\n \"fill-color\": DataDrivenProperty,\n \"fill-outline-color\": DataDrivenProperty,\n \"fill-translate\": DataConstantProperty<[number, number]>,\n \"fill-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"fill-pattern\": CrossFadedDataDrivenProperty,\n};\n\nexport type FillPaintPropsPossiblyEvaluated = {\n \"fill-antialias\": boolean,\n \"fill-opacity\": PossiblyEvaluatedPropertyValue,\n \"fill-color\": PossiblyEvaluatedPropertyValue,\n \"fill-outline-color\": PossiblyEvaluatedPropertyValue,\n \"fill-translate\": [number, number],\n \"fill-translate-anchor\": \"map\" | \"viewport\",\n \"fill-pattern\": PossiblyEvaluatedPropertyValue>,\n};\n\nlet paint: Properties;\nconst getPaint = () => paint = paint || new Properties({\n \"fill-antialias\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-antialias\"] as any as StylePropertySpecification),\n \"fill-opacity\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-opacity\"] as any as StylePropertySpecification),\n \"fill-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-color\"] as any as StylePropertySpecification),\n \"fill-outline-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-outline-color\"] as any as StylePropertySpecification),\n \"fill-translate\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate\"] as any as StylePropertySpecification),\n \"fill-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate-anchor\"] as any as StylePropertySpecification),\n \"fill-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-pattern\"] as any as StylePropertySpecification),\n});\n\nexport default ({ get paint() { return getPaint() }, get layout() { return getLayout() } });","import {StyleLayer} from '../style_layer';\n\nimport {FillBucket} from '../../data/bucket/fill_bucket';\nimport {polygonIntersectsMultiPolygon} from '../../util/intersection_tests';\nimport {translateDistance, translate} from '../query_utils';\nimport properties, {FillLayoutPropsPossiblyEvaluated, FillPaintPropsPossiblyEvaluated} from './fill_style_layer_properties.g';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties';\n\nimport type {FeatureState, LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {BucketParameters} from '../../data/bucket';\nimport type Point from '@mapbox/point-geometry';\nimport type {FillLayoutProps, FillPaintProps} from './fill_style_layer_properties.g';\nimport type {EvaluationParameters} from '../evaluation_parameters';\nimport type {Transform} from '../../geo/transform';\nimport type {VectorTileFeature} from '@mapbox/vector-tile';\n\nexport class FillStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout;\n layout: PossiblyEvaluated;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array) {\n super.recalculate(parameters, availableImages);\n\n const outlineColor = this.paint._values['fill-outline-color'];\n if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) {\n this.paint._values['fill-outline-color'] = this.paint._values['fill-color'];\n }\n }\n\n createBucket(parameters: BucketParameters) {\n return new FillBucket(parameters);\n }\n\n queryRadius(): number {\n return translateDistance(this.paint.get('fill-translate'));\n }\n\n queryIntersectsFeature(\n queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number\n ): boolean {\n const translatedPolygon = translate(queryGeometry,\n this.paint.get('fill-translate'),\n this.paint.get('fill-translate-anchor'),\n transform.angle, pixelsToTileUnits);\n return polygonIntersectsMultiPolygon(translatedPolygon, geometry);\n }\n\n isTileClipped() {\n return true;\n }\n}\n","import {createLayout} from '../../util/struct_array';\n\nconst layout = createLayout([\n {name: 'a_pos', components: 2, type: 'Int16'},\n {name: 'a_normal_ed', components: 4, type: 'Int16'},\n], 4);\n\nexport const centroidAttributes = createLayout([\n {name: 'a_centroid', components: 2, type: 'Int16'}\n], 4);\n\nexport default layout;\nexport const {members, size, alignment} = layout;\n","'use strict';\n\nvar Point = require('@mapbox/point-geometry');\n\nmodule.exports = VectorTileFeature;\n\nfunction VectorTileFeature(pbf, end, extent, keys, values) {\n // Public\n this.properties = {};\n this.extent = extent;\n this.type = 0;\n\n // Private\n this._pbf = pbf;\n this._geometry = -1;\n this._keys = keys;\n this._values = values;\n\n pbf.readFields(readFeature, this, end);\n}\n\nfunction readFeature(tag, feature, pbf) {\n if (tag == 1) feature.id = pbf.readVarint();\n else if (tag == 2) readTag(pbf, feature);\n else if (tag == 3) feature.type = pbf.readVarint();\n else if (tag == 4) feature._geometry = pbf.pos;\n}\n\nfunction readTag(pbf, feature) {\n var end = pbf.readVarint() + pbf.pos;\n\n while (pbf.pos < end) {\n var key = feature._keys[pbf.readVarint()],\n value = feature._values[pbf.readVarint()];\n feature.properties[key] = value;\n }\n}\n\nVectorTileFeature.types = ['Unknown', 'Point', 'LineString', 'Polygon'];\n\nVectorTileFeature.prototype.loadGeometry = function() {\n var pbf = this._pbf;\n pbf.pos = this._geometry;\n\n var end = pbf.readVarint() + pbf.pos,\n cmd = 1,\n length = 0,\n x = 0,\n y = 0,\n lines = [],\n line;\n\n while (pbf.pos < end) {\n if (length <= 0) {\n var cmdLen = pbf.readVarint();\n cmd = cmdLen & 0x7;\n length = cmdLen >> 3;\n }\n\n length--;\n\n if (cmd === 1 || cmd === 2) {\n x += pbf.readSVarint();\n y += pbf.readSVarint();\n\n if (cmd === 1) { // moveTo\n if (line) lines.push(line);\n line = [];\n }\n\n line.push(new Point(x, y));\n\n } else if (cmd === 7) {\n\n // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90\n if (line) {\n line.push(line[0].clone()); // closePolygon\n }\n\n } else {\n throw new Error('unknown command ' + cmd);\n }\n }\n\n if (line) lines.push(line);\n\n return lines;\n};\n\nVectorTileFeature.prototype.bbox = function() {\n var pbf = this._pbf;\n pbf.pos = this._geometry;\n\n var end = pbf.readVarint() + pbf.pos,\n cmd = 1,\n length = 0,\n x = 0,\n y = 0,\n x1 = Infinity,\n x2 = -Infinity,\n y1 = Infinity,\n y2 = -Infinity;\n\n while (pbf.pos < end) {\n if (length <= 0) {\n var cmdLen = pbf.readVarint();\n cmd = cmdLen & 0x7;\n length = cmdLen >> 3;\n }\n\n length--;\n\n if (cmd === 1 || cmd === 2) {\n x += pbf.readSVarint();\n y += pbf.readSVarint();\n if (x < x1) x1 = x;\n if (x > x2) x2 = x;\n if (y < y1) y1 = y;\n if (y > y2) y2 = y;\n\n } else if (cmd !== 7) {\n throw new Error('unknown command ' + cmd);\n }\n }\n\n return [x1, y1, x2, y2];\n};\n\nVectorTileFeature.prototype.toGeoJSON = function(x, y, z) {\n var size = this.extent * Math.pow(2, z),\n x0 = this.extent * x,\n y0 = this.extent * y,\n coords = this.loadGeometry(),\n type = VectorTileFeature.types[this.type],\n i, j;\n\n function project(line) {\n for (var j = 0; j < line.length; j++) {\n var p = line[j], y2 = 180 - (p.y + y0) * 360 / size;\n line[j] = [\n (p.x + x0) * 360 / size - 180,\n 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90\n ];\n }\n }\n\n switch (this.type) {\n case 1:\n var points = [];\n for (i = 0; i < coords.length; i++) {\n points[i] = coords[i][0];\n }\n coords = points;\n project(coords);\n break;\n\n case 2:\n for (i = 0; i < coords.length; i++) {\n project(coords[i]);\n }\n break;\n\n case 3:\n coords = classifyRings(coords);\n for (i = 0; i < coords.length; i++) {\n for (j = 0; j < coords[i].length; j++) {\n project(coords[i][j]);\n }\n }\n break;\n }\n\n if (coords.length === 1) {\n coords = coords[0];\n } else {\n type = 'Multi' + type;\n }\n\n var result = {\n type: \"Feature\",\n geometry: {\n type: type,\n coordinates: coords\n },\n properties: this.properties\n };\n\n if ('id' in this) {\n result.id = this.id;\n }\n\n return result;\n};\n\n// classifies an array of rings into polygons with outer rings and holes\n\nfunction classifyRings(rings) {\n var len = rings.length;\n\n if (len <= 1) return [rings];\n\n var polygons = [],\n polygon,\n ccw;\n\n for (var i = 0; i < len; i++) {\n var area = signedArea(rings[i]);\n if (area === 0) continue;\n\n if (ccw === undefined) ccw = area < 0;\n\n if (ccw === area < 0) {\n if (polygon) polygons.push(polygon);\n polygon = [rings[i]];\n\n } else {\n polygon.push(rings[i]);\n }\n }\n if (polygon) polygons.push(polygon);\n\n return polygons;\n}\n\nfunction signedArea(ring) {\n var sum = 0;\n for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {\n p1 = ring[i];\n p2 = ring[j];\n sum += (p2.x - p1.x) * (p1.y + p2.y);\n }\n return sum;\n}\n","'use strict';\n\nvar VectorTileFeature = require('./vectortilefeature.js');\n\nmodule.exports = VectorTileLayer;\n\nfunction VectorTileLayer(pbf, end) {\n // Public\n this.version = 1;\n this.name = null;\n this.extent = 4096;\n this.length = 0;\n\n // Private\n this._pbf = pbf;\n this._keys = [];\n this._values = [];\n this._features = [];\n\n pbf.readFields(readLayer, this, end);\n\n this.length = this._features.length;\n}\n\nfunction readLayer(tag, layer, pbf) {\n if (tag === 15) layer.version = pbf.readVarint();\n else if (tag === 1) layer.name = pbf.readString();\n else if (tag === 5) layer.extent = pbf.readVarint();\n else if (tag === 2) layer._features.push(pbf.pos);\n else if (tag === 3) layer._keys.push(pbf.readString());\n else if (tag === 4) layer._values.push(readValueMessage(pbf));\n}\n\nfunction readValueMessage(pbf) {\n var value = null,\n end = pbf.readVarint() + pbf.pos;\n\n while (pbf.pos < end) {\n var tag = pbf.readVarint() >> 3;\n\n value = tag === 1 ? pbf.readString() :\n tag === 2 ? pbf.readFloat() :\n tag === 3 ? pbf.readDouble() :\n tag === 4 ? pbf.readVarint64() :\n tag === 5 ? pbf.readVarint() :\n tag === 6 ? pbf.readSVarint() :\n tag === 7 ? pbf.readBoolean() : null;\n }\n\n return value;\n}\n\n// return feature `i` from this layer as a `VectorTileFeature`\nVectorTileLayer.prototype.feature = function(i) {\n if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds');\n\n this._pbf.pos = this._features[i];\n\n var end = this._pbf.readVarint() + this._pbf.pos;\n return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values);\n};\n","'use strict';\n\nvar VectorTileLayer = require('./vectortilelayer');\n\nmodule.exports = VectorTile;\n\nfunction VectorTile(pbf, end) {\n this.layers = pbf.readFields(readTile, {}, end);\n}\n\nfunction readTile(tag, layers, pbf) {\n if (tag === 3) {\n var layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos);\n if (layer.length) layers[layer.name] = layer;\n }\n}\n\n","module.exports.VectorTile = require('./lib/vectortile.js');\nmodule.exports.VectorTileFeature = require('./lib/vectortilefeature.js');\nmodule.exports.VectorTileLayer = require('./lib/vectortilelayer.js');\n","import {FillExtrusionLayoutArray, PosArray} from '../array_types.g';\n\nimport {members as layoutAttributes, centroidAttributes} from './fill_extrusion_attributes';\nimport {SegmentVector} from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {TriangleIndexArray} from '../index_array_type';\nimport {EXTENT} from '../extent';\nimport earcut from 'earcut';\nimport mvt from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = mvt.VectorTileFeature.types;\nimport {classifyRings} from '@maplibre/maplibre-gl-style-spec';\nconst EARCUT_MAX_RINGS = 500;\nimport {register} from '../../util/web_worker_transfer';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features';\nimport {loadGeometry} from '../load_geometry';\nimport {toEvaluationFeature} from '../evaluation_feature';\nimport {EvaluationParameters} from '../../style/evaluation_parameters';\n\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\n\nimport type {FillExtrusionStyleLayer} from '../../style/style_layer/fill_extrusion_style_layer';\nimport type {Context} from '../../gl/context';\nimport type {IndexBuffer} from '../../gl/index_buffer';\nimport type {VertexBuffer} from '../../gl/vertex_buffer';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\nimport type {VectorTileLayer} from '@mapbox/vector-tile';\n\nconst FACTOR = Math.pow(2, 13);\n\nfunction addVertex(vertexArray, x, y, nx, ny, nz, t, e) {\n vertexArray.emplaceBack(\n // a_pos\n x,\n y,\n // a_normal_ed: 3-component normal and 1-component edgedistance\n Math.floor(nx * FACTOR) * 2 + t,\n ny * FACTOR * 2,\n nz * FACTOR * 2,\n // edgedistance (used for wrapping patterns around extrusion sides)\n Math.round(e)\n );\n}\n\nexport class FillExtrusionBucket implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n layers: Array;\n layerIds: Array;\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n\n layoutVertexArray: FillExtrusionLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n centroidVertexArray: PosArray;\n centroidVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet;\n segments: SegmentVector;\n uploaded: boolean;\n features: Array;\n\n constructor(options: BucketParameters) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n\n this.layoutVertexArray = new FillExtrusionLayoutArray();\n this.centroidVertexArray = new PosArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.segments = new SegmentVector();\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID) {\n this.features = [];\n this.hasPattern = hasPattern('fill-extrusion', this.layers, options);\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n const needGeometry = this.layers[0]._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) continue;\n\n const bucketFeature: BucketFeature = {\n id,\n sourceLayerIndex,\n index,\n geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),\n properties: feature.properties,\n type: feature.type,\n patterns: {}\n };\n\n if (this.hasPattern) {\n this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, this.zoom, options));\n } else {\n this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {});\n }\n\n options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, true);\n }\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n for (const feature of this.features) {\n const {geometry} = feature;\n this.addFeature(feature, geometry, feature.index, canonical, imagePositions);\n }\n }\n\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);\n }\n\n isEmpty() {\n return this.layoutVertexArray.length === 0 && this.centroidVertexArray.length === 0;\n }\n\n uploadPending() {\n return !this.uploaded || this.programConfigurations.needsUpload;\n }\n\n upload(context: Context) {\n if (!this.uploaded) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n }\n this.programConfigurations.upload(context);\n this.uploaded = true;\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n this.centroidVertexBuffer.destroy();\n }\n\n addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n for (const polygon of classifyRings(geometry, EARCUT_MAX_RINGS)) {\n\n const centroid = {x: 0, y: 0, vertexCount: 0};\n\n let numVertices = 0;\n for (const ring of polygon) {\n numVertices += ring.length;\n }\n let segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray);\n\n for (const ring of polygon) {\n if (ring.length === 0) {\n continue;\n }\n\n if (isEntirelyOutside(ring)) {\n continue;\n }\n\n let edgeDistance = 0;\n\n for (let p = 0; p < ring.length; p++) {\n const p1 = ring[p];\n\n if (p >= 1) {\n const p2 = ring[p - 1];\n\n if (!isBoundaryEdge(p1, p2)) {\n if (segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {\n segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray);\n }\n\n const perp = p1.sub(p2)._perp()._unit();\n const dist = p2.dist(p1);\n if (edgeDistance + dist > 32768) edgeDistance = 0;\n\n addVertex(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 0, edgeDistance);\n addVertex(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 1, edgeDistance);\n centroid.x += 2 * p1.x;\n centroid.y += 2 * p1.y;\n centroid.vertexCount += 2;\n\n edgeDistance += dist;\n\n addVertex(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 0, edgeDistance);\n addVertex(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 1, edgeDistance);\n centroid.x += 2 * p2.x;\n centroid.y += 2 * p2.y;\n centroid.vertexCount += 2;\n\n const bottomRight = segment.vertexLength;\n\n // ┌──────┐\n // │ 0 1 │ Counter-clockwise winding order.\n // │ │ Triangle 1: 0 => 2 => 1\n // │ 2 3 │ Triangle 2: 1 => 2 => 3\n // └──────┘\n this.indexArray.emplaceBack(bottomRight, bottomRight + 2, bottomRight + 1);\n this.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3);\n\n segment.vertexLength += 4;\n segment.primitiveLength += 2;\n }\n }\n }\n\n }\n\n if (segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {\n segment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray);\n }\n\n //Only triangulate and draw the area of the feature if it is a polygon\n //Other feature types (e.g. LineString) do not have area, so triangulation is pointless / undefined\n if (vectorTileFeatureTypes[feature.type] !== 'Polygon')\n continue;\n\n const flattened = [];\n const holeIndices = [];\n const triangleIndex = segment.vertexLength;\n\n for (const ring of polygon) {\n if (ring.length === 0) {\n continue;\n }\n\n if (ring !== polygon[0]) {\n holeIndices.push(flattened.length / 2);\n }\n\n for (let i = 0; i < ring.length; i++) {\n const p = ring[i];\n\n addVertex(this.layoutVertexArray, p.x, p.y, 0, 0, 1, 1, 0);\n centroid.x += p.x;\n centroid.y += p.y;\n centroid.vertexCount += 1;\n\n flattened.push(p.x);\n flattened.push(p.y);\n }\n\n }\n\n const indices = earcut(flattened, holeIndices);\n\n for (let j = 0; j < indices.length; j += 3) {\n // Counter-clockwise winding order.\n this.indexArray.emplaceBack(\n triangleIndex + indices[j],\n triangleIndex + indices[j + 2],\n triangleIndex + indices[j + 1]);\n }\n\n segment.primitiveLength += indices.length / 3;\n segment.vertexLength += numVertices;\n\n // remember polygon centroid to calculate elevation in GPU\n for (let i = 0; i < centroid.vertexCount; i++) {\n const averageX = Math.floor(centroid.x / centroid.vertexCount);\n const averageY = Math.floor(centroid.y / centroid.vertexCount);\n this.centroidVertexArray.emplaceBack(averageX, averageY);\n }\n\n }\n\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical);\n }\n}\n\nregister('FillExtrusionBucket', FillExtrusionBucket, {omit: ['layers', 'features']});\n\nfunction isBoundaryEdge(p1, p2) {\n return (p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT)) ||\n (p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT));\n}\n\nfunction isEntirelyOutside(ring) {\n return ring.every(p => p.x < 0) ||\n ring.every(p => p.x > EXTENT) ||\n ring.every(p => p.y < 0) ||\n ring.every(p => p.y > EXTENT);\n}\n","// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty,\n PossiblyEvaluatedPropertyValue,\n CrossFaded\n} from '../properties';\n\nimport type {Color, Formatted, Padding, ResolvedImage, VariableAnchorOffsetCollection} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type FillExtrusionPaintProps = {\n \"fill-extrusion-opacity\": DataConstantProperty,\n \"fill-extrusion-color\": DataDrivenProperty,\n \"fill-extrusion-translate\": DataConstantProperty<[number, number]>,\n \"fill-extrusion-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"fill-extrusion-pattern\": CrossFadedDataDrivenProperty,\n \"fill-extrusion-height\": DataDrivenProperty,\n \"fill-extrusion-base\": DataDrivenProperty,\n \"fill-extrusion-vertical-gradient\": DataConstantProperty,\n};\n\nexport type FillExtrusionPaintPropsPossiblyEvaluated = {\n \"fill-extrusion-opacity\": number,\n \"fill-extrusion-color\": PossiblyEvaluatedPropertyValue,\n \"fill-extrusion-translate\": [number, number],\n \"fill-extrusion-translate-anchor\": \"map\" | \"viewport\",\n \"fill-extrusion-pattern\": PossiblyEvaluatedPropertyValue>,\n \"fill-extrusion-height\": PossiblyEvaluatedPropertyValue,\n \"fill-extrusion-base\": PossiblyEvaluatedPropertyValue,\n \"fill-extrusion-vertical-gradient\": boolean,\n};\n\nlet paint: Properties;\nconst getPaint = () => paint = paint || new Properties({\n \"fill-extrusion-opacity\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-opacity\"] as any as StylePropertySpecification),\n \"fill-extrusion-color\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-color\"] as any as StylePropertySpecification),\n \"fill-extrusion-translate\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate\"] as any as StylePropertySpecification),\n \"fill-extrusion-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate-anchor\"] as any as StylePropertySpecification),\n \"fill-extrusion-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-pattern\"] as any as StylePropertySpecification),\n \"fill-extrusion-height\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-height\"] as any as StylePropertySpecification),\n \"fill-extrusion-base\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-base\"] as any as StylePropertySpecification),\n \"fill-extrusion-vertical-gradient\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-vertical-gradient\"] as any as StylePropertySpecification),\n});\n\nexport default ({ get paint() { return getPaint() } });","import {StyleLayer} from '../style_layer';\n\nimport {FillExtrusionBucket} from '../../data/bucket/fill_extrusion_bucket';\nimport {polygonIntersectsPolygon, polygonIntersectsMultiPolygon} from '../../util/intersection_tests';\nimport {translateDistance, translate} from '../query_utils';\nimport properties, {FillExtrusionPaintPropsPossiblyEvaluated} from './fill_extrusion_style_layer_properties.g';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\nimport {mat4, vec4} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\nimport type {FeatureState, LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {BucketParameters} from '../../data/bucket';\nimport type {FillExtrusionPaintProps} from './fill_extrusion_style_layer_properties.g';\nimport type {Transform} from '../../geo/transform';\nimport type {VectorTileFeature} from '@mapbox/vector-tile';\n\nexport class Point3D extends Point {\n z: number;\n}\n\nexport class FillExtrusionStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n createBucket(parameters: BucketParameters) {\n return new FillExtrusionBucket(parameters);\n }\n\n queryRadius(): number {\n return translateDistance(this.paint.get('fill-extrusion-translate'));\n }\n\n is3D(): boolean {\n return true;\n }\n\n queryIntersectsFeature(\n queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number,\n pixelPosMatrix: mat4\n ): boolean | number {\n\n const translatedPolygon = translate(queryGeometry,\n this.paint.get('fill-extrusion-translate'),\n this.paint.get('fill-extrusion-translate-anchor'),\n transform.angle, pixelsToTileUnits);\n\n const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState);\n const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState);\n\n const projectedQueryGeometry = projectQueryGeometry(translatedPolygon, pixelPosMatrix, transform, 0);\n\n const projected = projectExtrusion(geometry, base, height, pixelPosMatrix);\n const projectedBase = projected[0];\n const projectedTop = projected[1];\n return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry);\n }\n}\n\nfunction dot(a, b) {\n return a.x * b.x + a.y * b.y;\n}\n\nexport function getIntersectionDistance(projectedQueryGeometry: Array, projectedFace: Array) {\n\n if (projectedQueryGeometry.length === 1) {\n // For point queries calculate the z at which the point intersects the face\n // using barycentric coordinates.\n\n // Find the barycentric coordinates of the projected point within the first\n // triangle of the face, using only the xy plane. It doesn't matter if the\n // point is outside the first triangle because all the triangles in the face\n // are in the same plane.\n //\n // Check whether points are coincident and use other points if they are.\n let i = 0;\n const a = projectedFace[i++];\n let b;\n while (!b || a.equals(b)) {\n b = projectedFace[i++];\n if (!b) return Infinity;\n }\n\n // Loop until point `c` is not colinear with points `a` and `b`.\n for (; i < projectedFace.length; i++) {\n const c = projectedFace[i];\n\n const p = projectedQueryGeometry[0];\n\n const ab = b.sub(a);\n const ac = c.sub(a);\n const ap = p.sub(a);\n\n const dotABAB = dot(ab, ab);\n const dotABAC = dot(ab, ac);\n const dotACAC = dot(ac, ac);\n const dotAPAB = dot(ap, ab);\n const dotAPAC = dot(ap, ac);\n const denom = dotABAB * dotACAC - dotABAC * dotABAC;\n\n const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom;\n const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom;\n const u = 1 - v - w;\n\n // Use the barycentric weighting along with the original triangle z coordinates to get the point of intersection.\n const distance = a.z * u + b.z * v + c.z * w;\n\n if (isFinite(distance)) return distance;\n }\n\n return Infinity;\n\n } else {\n // The counts as closest is less clear when the query is a box. This\n // returns the distance to the nearest point on the face, whether it is\n // within the query or not. It could be more correct to return the\n // distance to the closest point within the query box but this would be\n // more complicated and expensive to calculate with little benefit.\n let closestDistance = Infinity;\n for (const p of projectedFace) {\n closestDistance = Math.min(closestDistance, p.z);\n }\n return closestDistance;\n }\n}\n\nfunction checkIntersection(projectedBase: Array>, projectedTop: Array>, projectedQueryGeometry: Array) {\n let closestDistance = Infinity;\n\n if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) {\n closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]);\n }\n\n for (let r = 0; r < projectedTop.length; r++) {\n const ringTop = projectedTop[r];\n const ringBase = projectedBase[r];\n for (let p = 0; p < ringTop.length - 1; p++) {\n const topA = ringTop[p];\n const topB = ringTop[p + 1];\n const baseA = ringBase[p];\n const baseB = ringBase[p + 1];\n const face = [topA, topB, baseB, baseA, topA];\n if (polygonIntersectsPolygon(projectedQueryGeometry, face)) {\n closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face));\n }\n }\n }\n\n return closestDistance === Infinity ? false : closestDistance;\n}\n\n/*\n * Project the geometry using matrix `m`. This is essentially doing\n * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication\n * is inlined so that parts of the projection that are the same across\n * different points can only be done once. This produced a measurable\n * performance improvement.\n */\nfunction projectExtrusion(geometry: Array>, zBase: number, zTop: number, m: mat4): [Array>, Array>] {\n const projectedBase = [] as Array>;\n const projectedTop = [] as Array>;\n const baseXZ = m[8] * zBase;\n const baseYZ = m[9] * zBase;\n const baseZZ = m[10] * zBase;\n const baseWZ = m[11] * zBase;\n const topXZ = m[8] * zTop;\n const topYZ = m[9] * zTop;\n const topZZ = m[10] * zTop;\n const topWZ = m[11] * zTop;\n\n for (const r of geometry) {\n const ringBase = [] as Array;\n const ringTop = [] as Array;\n for (const p of r) {\n const x = p.x;\n const y = p.y;\n\n const sX = m[0] * x + m[4] * y + m[12];\n const sY = m[1] * x + m[5] * y + m[13];\n const sZ = m[2] * x + m[6] * y + m[14];\n const sW = m[3] * x + m[7] * y + m[15];\n\n const baseX = sX + baseXZ;\n const baseY = sY + baseYZ;\n const baseZ = sZ + baseZZ;\n const baseW = sW + baseWZ;\n\n const topX = sX + topXZ;\n const topY = sY + topYZ;\n const topZ = sZ + topZZ;\n const topW = sW + topWZ;\n\n const b = new Point(baseX / baseW, baseY / baseW) as Point3D;\n b.z = baseZ / baseW;\n ringBase.push(b);\n\n const t = new Point(topX / topW, topY / topW) as Point3D;\n t.z = topZ / topW;\n ringTop.push(t);\n }\n projectedBase.push(ringBase);\n projectedTop.push(ringTop);\n }\n return [projectedBase, projectedTop];\n}\n\nfunction projectQueryGeometry(queryGeometry: Array, pixelPosMatrix: mat4, transform: Transform, z: number) {\n const projectedQueryGeometry = [];\n for (const p of queryGeometry) {\n const v = [p.x, p.y, z, 1] as vec4;\n vec4.transformMat4(v, v, pixelPosMatrix);\n projectedQueryGeometry.push(new Point(v[0] / v[3], v[1] / v[3]));\n }\n return projectedQueryGeometry;\n}\n","import {createLayout} from '../../util/struct_array';\n\nexport const lineLayoutAttributes = createLayout([\n {name: 'a_pos_normal', components: 2, type: 'Int16'},\n {name: 'a_data', components: 4, type: 'Uint8'}\n], 4);\n\nexport const {members, size, alignment} = lineLayoutAttributes;\n","import {createLayout} from '../../util/struct_array';\n\nexport const lineLayoutAttributesExt = createLayout([\n {name: 'a_uv_x', components: 1, type: 'Float32'},\n {name: 'a_split_index', components: 1, type: 'Float32'},\n]);\n\nexport const {members, size, alignment} = lineLayoutAttributesExt;\n","import {LineLayoutArray, LineExtLayoutArray} from '../array_types.g';\n\nimport {members as layoutAttributes} from './line_attributes';\nimport {members as layoutAttributesExt} from './line_attributes_ext';\nimport {SegmentVector} from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {TriangleIndexArray} from '../index_array_type';\nimport {EXTENT} from '../extent';\nimport mvt from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = mvt.VectorTileFeature.types;\nimport {register} from '../../util/web_worker_transfer';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features';\nimport {loadGeometry} from '../load_geometry';\nimport {toEvaluationFeature} from '../evaluation_feature';\nimport {EvaluationParameters} from '../../style/evaluation_parameters';\n\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\nimport type {LineStyleLayer} from '../../style/style_layer/line_style_layer';\nimport type Point from '@mapbox/point-geometry';\nimport type {Segment} from '../segment';\nimport {RGBAImage} from '../../util/image';\nimport type {Context} from '../../gl/context';\nimport type {Texture} from '../../render/texture';\nimport type {IndexBuffer} from '../../gl/index_buffer';\nimport type {VertexBuffer} from '../../gl/vertex_buffer';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\nimport type {VectorTileLayer} from '@mapbox/vector-tile';\n\n// NOTE ON EXTRUDE SCALE:\n// scale the extrusion vector so that the normal length is this value.\n// contains the \"texture\" normals (-1..1). this is distinct from the extrude\n// normals for line joins, because the x-value remains 0 for the texture\n// normal array, while the extrude normal actually moves the vertex to create\n// the acute/bevelled line join.\nconst EXTRUDE_SCALE = 63;\n\n/*\n * Sharp corners cause dashed lines to tilt because the distance along the line\n * is the same at both the inner and outer corners. To improve the appearance of\n * dashed lines we add extra points near sharp corners so that a smaller part\n * of the line is tilted.\n *\n * COS_HALF_SHARP_CORNER controls how sharp a corner has to be for us to add an\n * extra vertex. The default is 75 degrees.\n *\n * The newly created vertices are placed SHARP_CORNER_OFFSET pixels from the corner.\n */\nconst COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180));\nconst SHARP_CORNER_OFFSET = 15;\n\n// Angle per triangle for approximating round line joins.\nconst DEG_PER_TRIANGLE = 20;\n\n// The number of bits that is used to store the line distance in the buffer.\nconst LINE_DISTANCE_BUFFER_BITS = 15;\n\n// We don't have enough bits for the line distance as we'd like to have, so\n// use this value to scale the line distance (in tile units) down to a smaller\n// value. This lets us store longer distances while sacrificing precision.\nconst LINE_DISTANCE_SCALE = 1 / 2;\n\n// The maximum line distance, in tile units, that fits in the buffer.\nconst MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE;\n\ntype LineClips = {\n start: number;\n end: number;\n};\n\ntype GradientTexture = {\n texture?: Texture;\n gradient?: RGBAImage;\n version?: number;\n};\n\n/**\n * @internal\n * Line bucket class\n */\nexport class LineBucket implements Bucket {\n distance: number;\n totalDistance: number;\n maxLineLength: number;\n scaledDistance: number;\n lineClips?: LineClips;\n\n e1: number;\n e2: number;\n\n index: number;\n zoom: number;\n overscaling: number;\n layers: Array;\n layerIds: Array;\n gradients: {[x: string]: GradientTexture};\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n patternFeatures: Array;\n lineClipsArray: Array;\n\n layoutVertexArray: LineLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n layoutVertexArray2: LineExtLayoutArray;\n layoutVertexBuffer2: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet;\n segments: SegmentVector;\n uploaded: boolean;\n\n constructor(options: BucketParameters) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n this.patternFeatures = [];\n this.lineClipsArray = [];\n this.gradients = {};\n this.layers.forEach(layer => {\n this.gradients[layer.id] = {};\n });\n\n this.layoutVertexArray = new LineLayoutArray();\n this.layoutVertexArray2 = new LineExtLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.segments = new SegmentVector();\n this.maxLineLength = 0;\n\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID) {\n this.hasPattern = hasPattern('line', this.layers, options);\n const lineSortKey = this.layers[0].layout.get('line-sort-key');\n const sortFeaturesByKey = !lineSortKey.isConstant();\n const bucketFeatures: BucketFeature[] = [];\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n const needGeometry = this.layers[0]._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) continue;\n\n const sortKey = sortFeaturesByKey ?\n lineSortKey.evaluate(evaluationFeature, {}, canonical) :\n undefined;\n\n const bucketFeature: BucketFeature = {\n id,\n properties: feature.properties,\n type: feature.type,\n sourceLayerIndex,\n index,\n geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),\n patterns: {},\n sortKey\n };\n\n bucketFeatures.push(bucketFeature);\n }\n\n if (sortFeaturesByKey) {\n bucketFeatures.sort((a, b) => {\n return (a.sortKey) - (b.sortKey);\n });\n }\n\n for (const bucketFeature of bucketFeatures) {\n const {geometry, index, sourceLayerIndex} = bucketFeature;\n\n if (this.hasPattern) {\n const patternBucketFeature = addPatternDependencies('line', this.layers, bucketFeature, this.zoom, options);\n // pattern features are added only once the pattern is loaded into the image atlas\n // so are stored during populate until later updated with positions by tile worker in addFeatures\n this.patternFeatures.push(patternBucketFeature);\n } else {\n this.addFeature(bucketFeature, geometry, index, canonical, {});\n }\n\n const feature = features[index].feature;\n options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n }\n }\n\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n for (const feature of this.patternFeatures) {\n this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions);\n }\n }\n\n isEmpty() {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending() {\n return !this.uploaded || this.programConfigurations.needsUpload;\n }\n\n upload(context: Context) {\n if (!this.uploaded) {\n if (this.layoutVertexArray2.length !== 0) {\n this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, layoutAttributesExt);\n }\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n }\n this.programConfigurations.upload(context);\n this.uploaded = true;\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n }\n\n lineFeatureClips(feature: BucketFeature): LineClips | undefined {\n if (!!feature.properties && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_start') && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_end')) {\n const start = +feature.properties['mapbox_clip_start'];\n const end = +feature.properties['mapbox_clip_end'];\n return {start, end};\n }\n }\n\n addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n const layout = this.layers[0].layout;\n const join = layout.get('line-join').evaluate(feature, {});\n const cap = layout.get('line-cap');\n const miterLimit = layout.get('line-miter-limit');\n const roundLimit = layout.get('line-round-limit');\n this.lineClips = this.lineFeatureClips(feature);\n\n for (const line of geometry) {\n this.addLine(line, feature, join, cap, miterLimit, roundLimit);\n }\n\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical);\n }\n\n addLine(vertices: Array, feature: BucketFeature, join: string, cap: string, miterLimit: number, roundLimit: number) {\n this.distance = 0;\n this.scaledDistance = 0;\n this.totalDistance = 0;\n\n if (this.lineClips) {\n this.lineClipsArray.push(this.lineClips);\n // Calculate the total distance, in tile units, of this tiled line feature\n for (let i = 0; i < vertices.length - 1; i++) {\n this.totalDistance += vertices[i].dist(vertices[i + 1]);\n }\n this.updateScaledDistance();\n this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance);\n }\n\n const isPolygon = vectorTileFeatureTypes[feature.type] === 'Polygon';\n\n // If the line has duplicate vertices at the ends, adjust start/length to remove them.\n let len = vertices.length;\n while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) {\n len--;\n }\n let first = 0;\n while (first < len - 1 && vertices[first].equals(vertices[first + 1])) {\n first++;\n }\n\n // Ignore invalid geometry.\n if (len < (isPolygon ? 3 : 2)) return;\n\n if (join === 'bevel') miterLimit = 1.05;\n\n const sharpCornerOffset = this.overscaling <= 16 ?\n SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) :\n 0;\n\n // we could be more precise, but it would only save a negligible amount of space\n const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray);\n\n let currentVertex: Point;\n let prevVertex: Point;\n let nextVertex: Point;\n let prevNormal: Point;\n let nextNormal: Point;\n\n // the last two vertices added\n this.e1 = this.e2 = -1;\n\n if (isPolygon) {\n currentVertex = vertices[len - 2];\n nextNormal = vertices[first].sub(currentVertex)._unit()._perp();\n }\n\n for (let i = first; i < len; i++) {\n\n nextVertex = i === len - 1 ?\n (isPolygon ? vertices[first + 1] : undefined) : // if it's a polygon, treat the last vertex like the first\n vertices[i + 1]; // just the next vertex\n\n // if two consecutive vertices exist, skip the current one\n if (nextVertex && vertices[i].equals(nextVertex)) continue;\n\n if (nextNormal) prevNormal = nextNormal;\n if (currentVertex) prevVertex = currentVertex;\n\n currentVertex = vertices[i];\n\n // Calculate the normal towards the next vertex in this line. In case\n // there is no next vertex, pretend that the line is continuing straight,\n // meaning that we are just using the previous normal.\n nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal;\n\n // If we still don't have a previous normal, this is the beginning of a\n // non-closed line, so we're doing a straight \"join\".\n prevNormal = prevNormal || nextNormal;\n\n // Determine the normal of the join extrusion. It is the angle bisector\n // of the segments between the previous line and the next line.\n // In the case of 180° angles, the prev and next normals cancel each other out:\n // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be\n // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle\n // below will also become 0 and miterLength will become Infinity.\n let joinNormal = prevNormal.add(nextNormal);\n if (joinNormal.x !== 0 || joinNormal.y !== 0) {\n joinNormal._unit();\n }\n /* joinNormal prevNormal\n * ↖ ↑\n * .________. prevVertex\n * |\n * nextNormal ← | currentVertex\n * |\n * nextVertex !\n *\n */\n\n // calculate cosines of the angle (and its half) using dot product\n const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y;\n const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;\n\n // Calculate the length of the miter (the ratio of the miter to the width)\n // as the inverse of cosine of the angle between next and join normals\n const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity;\n\n // approximate angle from cosine\n const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle);\n\n const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex;\n const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0;\n\n if (isSharpCorner && i > first) {\n const prevSegmentLength = currentVertex.dist(prevVertex);\n if (prevSegmentLength > 2 * sharpCornerOffset) {\n const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round());\n this.updateDistance(prevVertex, newPrevVertex);\n this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment);\n prevVertex = newPrevVertex;\n }\n }\n\n // The join if a middle vertex, otherwise the cap.\n const middleVertex = prevVertex && nextVertex;\n let currentJoin = middleVertex ? join : isPolygon ? 'butt' : cap;\n\n if (middleVertex && currentJoin === 'round') {\n if (miterLength < roundLimit) {\n currentJoin = 'miter';\n } else if (miterLength <= 2) {\n currentJoin = 'fakeround';\n }\n }\n\n if (currentJoin === 'miter' && miterLength > miterLimit) {\n currentJoin = 'bevel';\n }\n\n if (currentJoin === 'bevel') {\n // The maximum extrude length is 128 / 63 = 2 times the width of the line\n // so if miterLength >= 2 we need to draw a different type of bevel here.\n if (miterLength > 2) currentJoin = 'flipbevel';\n\n // If the miterLength is really small and the line bevel wouldn't be visible,\n // just draw a miter join to save a triangle.\n if (miterLength < miterLimit) currentJoin = 'miter';\n }\n\n // Calculate how far along the line the currentVertex is\n if (prevVertex) this.updateDistance(prevVertex, currentVertex);\n\n if (currentJoin === 'miter') {\n\n joinNormal._mult(miterLength);\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);\n\n } else if (currentJoin === 'flipbevel') {\n // miter is too big, flip the direction to make a beveled join\n\n if (miterLength > 100) {\n // Almost parallel lines\n joinNormal = nextNormal.mult(-1);\n\n } else {\n const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag();\n joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1));\n }\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);\n this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment);\n\n } else if (currentJoin === 'bevel' || currentJoin === 'fakeround') {\n const offset = -Math.sqrt(miterLength * miterLength - 1);\n const offsetA = lineTurnsLeft ? offset : 0;\n const offsetB = lineTurnsLeft ? 0 : offset;\n\n // Close previous segment with a bevel\n if (prevVertex) {\n this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment);\n }\n\n if (currentJoin === 'fakeround') {\n // The join angle is sharp enough that a round join would be visible.\n // Bevel joins fill the gap between segments with a single pie slice triangle.\n // Create a round join by adding multiple pie slices. The join isn't actually round, but\n // it looks like it is at the sizes we render lines at.\n\n // pick the number of triangles for approximating round join by based on the angle between normals\n const n = Math.round((approxAngle * 180 / Math.PI) / DEG_PER_TRIANGLE);\n\n for (let m = 1; m < n; m++) {\n let t = m / n;\n if (t !== 0.5) {\n // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp\n const t2 = t - 0.5;\n const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519));\n const B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638);\n t = t + t * t2 * (t - 1) * (A * t2 * t2 + B);\n }\n const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1);\n this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment);\n }\n }\n\n if (nextVertex) {\n // Start next segment\n this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment);\n }\n\n } else if (currentJoin === 'butt') {\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); // butt cap\n\n } else if (currentJoin === 'square') {\n const offset = prevVertex ? 1 : -1; // closing or starting square cap\n this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment);\n\n } else if (currentJoin === 'round') {\n\n if (prevVertex) {\n // Close previous segment with butt\n this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment);\n\n // Add round cap or linejoin at end of segment\n this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true);\n }\n if (nextVertex) {\n // Add round cap before first segment\n this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true);\n\n // Start next segment with a butt\n this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment);\n }\n }\n\n if (isSharpCorner && i < len - 1) {\n const nextSegmentLength = currentVertex.dist(nextVertex);\n if (nextSegmentLength > 2 * sharpCornerOffset) {\n const newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round());\n this.updateDistance(currentVertex, newCurrentVertex);\n this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment);\n currentVertex = newCurrentVertex;\n }\n }\n }\n }\n\n /**\n * Add two vertices to the buffers.\n *\n * @param p - the line vertex to add buffer vertices for\n * @param normal - vertex normal\n * @param endLeft - extrude to shift the left vertex along the line\n * @param endRight - extrude to shift the left vertex along the line\n * @param segment - the segment object to add the vertex to\n * @param round - whether this is a round cap\n */\n addCurrentVertex(p: Point, normal: Point, endLeft: number, endRight: number, segment: Segment, round: boolean = false) {\n // left and right extrude vectors, perpendicularly shifted by endLeft/endRight\n const leftX = normal.x + normal.y * endLeft;\n const leftY = normal.y - normal.x * endLeft;\n const rightX = -normal.x + normal.y * endRight;\n const rightY = -normal.y - normal.x * endRight;\n\n this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment);\n this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment);\n\n // There is a maximum \"distance along the line\" that we can store in the buffers.\n // When we get close to the distance, reset it to zero and add the vertex again with\n // a distance of zero. The max distance is determined by the number of bits we allocate\n // to `linesofar`.\n if (this.distance > MAX_LINE_DISTANCE / 2 && this.totalDistance === 0) {\n this.distance = 0;\n this.updateScaledDistance();\n this.addCurrentVertex(p, normal, endLeft, endRight, segment, round);\n }\n }\n\n addHalfVertex({x, y}: Point, extrudeX: number, extrudeY: number, round: boolean, up: boolean, dir: number, segment: Segment) {\n const totalDistance = this.lineClips ? this.scaledDistance * (MAX_LINE_DISTANCE - 1) : this.scaledDistance;\n // scale down so that we can store longer distances while sacrificing precision.\n const linesofarScaled = totalDistance * LINE_DISTANCE_SCALE;\n\n this.layoutVertexArray.emplaceBack(\n // a_pos_normal\n // Encode round/up the least significant bits\n (x << 1) + (round ? 1 : 0),\n (y << 1) + (up ? 1 : 0),\n // a_data\n // add 128 to store a byte in an unsigned byte\n Math.round(EXTRUDE_SCALE * extrudeX) + 128,\n Math.round(EXTRUDE_SCALE * extrudeY) + 128,\n // Encode the -1/0/1 direction value into the first two bits of .z of a_data.\n // Combine it with the lower 6 bits of `linesofarScaled` (shifted by 2 bits to make\n // room for the direction value). The upper 8 bits of `linesofarScaled` are placed in\n // the `w` component.\n ((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | ((linesofarScaled & 0x3F) << 2),\n linesofarScaled >> 6);\n\n // Constructs a second vertex buffer with higher precision line progress\n if (this.lineClips) {\n const progressRealigned = this.scaledDistance - this.lineClips.start;\n const endClipRealigned = this.lineClips.end - this.lineClips.start;\n const uvX = progressRealigned / endClipRealigned;\n this.layoutVertexArray2.emplaceBack(uvX, this.lineClipsArray.length);\n }\n\n const e = segment.vertexLength++;\n if (this.e1 >= 0 && this.e2 >= 0) {\n this.indexArray.emplaceBack(this.e1, this.e2, e);\n segment.primitiveLength++;\n }\n if (up) {\n this.e2 = e;\n } else {\n this.e1 = e;\n }\n }\n\n updateScaledDistance() {\n // Knowing the ratio of the full linestring covered by this tiled feature, as well\n // as the total distance (in tile units) of this tiled feature, and the distance\n // (in tile units) of the current vertex, we can determine the relative distance\n // of this vertex along the full linestring feature and scale it to [0, 2^15)\n this.scaledDistance = this.lineClips ?\n this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance :\n this.distance;\n }\n\n updateDistance(prev: Point, next: Point) {\n this.distance += prev.dist(next);\n this.updateScaledDistance();\n }\n}\n\nregister('LineBucket', LineBucket, {omit: ['layers', 'patternFeatures']});\n","// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty,\n PossiblyEvaluatedPropertyValue,\n CrossFaded\n} from '../properties';\n\nimport type {Color, Formatted, Padding, ResolvedImage, VariableAnchorOffsetCollection} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport type LineLayoutProps = {\n \"line-cap\": DataConstantProperty<\"butt\" | \"round\" | \"square\">,\n \"line-join\": DataDrivenProperty<\"bevel\" | \"round\" | \"miter\">,\n \"line-miter-limit\": DataConstantProperty,\n \"line-round-limit\": DataConstantProperty,\n \"line-sort-key\": DataDrivenProperty,\n};\n\nexport type LineLayoutPropsPossiblyEvaluated = {\n \"line-cap\": \"butt\" | \"round\" | \"square\",\n \"line-join\": PossiblyEvaluatedPropertyValue<\"bevel\" | \"round\" | \"miter\">,\n \"line-miter-limit\": number,\n \"line-round-limit\": number,\n \"line-sort-key\": PossiblyEvaluatedPropertyValue,\n};\n\nlet layout: Properties;\nconst getLayout = () => layout = layout || new Properties({\n \"line-cap\": new DataConstantProperty(styleSpec[\"layout_line\"][\"line-cap\"] as any as StylePropertySpecification),\n \"line-join\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-join\"] as any as StylePropertySpecification),\n \"line-miter-limit\": new DataConstantProperty(styleSpec[\"layout_line\"][\"line-miter-limit\"] as any as StylePropertySpecification),\n \"line-round-limit\": new DataConstantProperty(styleSpec[\"layout_line\"][\"line-round-limit\"] as any as StylePropertySpecification),\n \"line-sort-key\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-sort-key\"] as any as StylePropertySpecification),\n});\n\nexport type LinePaintProps = {\n \"line-opacity\": DataDrivenProperty,\n \"line-color\": DataDrivenProperty,\n \"line-translate\": DataConstantProperty<[number, number]>,\n \"line-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"line-width\": DataDrivenProperty,\n \"line-gap-width\": DataDrivenProperty,\n \"line-offset\": DataDrivenProperty,\n \"line-blur\": DataDrivenProperty,\n \"line-dasharray\": CrossFadedProperty>,\n \"line-pattern\": CrossFadedDataDrivenProperty,\n \"line-gradient\": ColorRampProperty,\n};\n\nexport type LinePaintPropsPossiblyEvaluated = {\n \"line-opacity\": PossiblyEvaluatedPropertyValue,\n \"line-color\": PossiblyEvaluatedPropertyValue,\n \"line-translate\": [number, number],\n \"line-translate-anchor\": \"map\" | \"viewport\",\n \"line-width\": PossiblyEvaluatedPropertyValue,\n \"line-gap-width\": PossiblyEvaluatedPropertyValue,\n \"line-offset\": PossiblyEvaluatedPropertyValue,\n \"line-blur\": PossiblyEvaluatedPropertyValue,\n \"line-dasharray\": CrossFaded>,\n \"line-pattern\": PossiblyEvaluatedPropertyValue>,\n \"line-gradient\": ColorRampProperty,\n};\n\nlet paint: Properties;\nconst getPaint = () => paint = paint || new Properties({\n \"line-opacity\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-opacity\"] as any as StylePropertySpecification),\n \"line-color\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-color\"] as any as StylePropertySpecification),\n \"line-translate\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate\"] as any as StylePropertySpecification),\n \"line-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate-anchor\"] as any as StylePropertySpecification),\n \"line-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-width\"] as any as StylePropertySpecification),\n \"line-gap-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-gap-width\"] as any as StylePropertySpecification),\n \"line-offset\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-offset\"] as any as StylePropertySpecification),\n \"line-blur\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-blur\"] as any as StylePropertySpecification),\n \"line-dasharray\": new CrossFadedProperty(styleSpec[\"paint_line\"][\"line-dasharray\"] as any as StylePropertySpecification),\n \"line-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_line\"][\"line-pattern\"] as any as StylePropertySpecification),\n \"line-gradient\": new ColorRampProperty(styleSpec[\"paint_line\"][\"line-gradient\"] as any as StylePropertySpecification),\n});\n\nexport default ({ get paint() { return getPaint() }, get layout() { return getLayout() } });","import Point from '@mapbox/point-geometry';\n\nimport {StyleLayer} from '../style_layer';\nimport {LineBucket} from '../../data/bucket/line_bucket';\nimport {polygonIntersectsBufferedMultiLine} from '../../util/intersection_tests';\nimport {getMaximumPaintValue, translateDistance, translate, offsetLine} from '../query_utils';\nimport properties, {LineLayoutPropsPossiblyEvaluated, LinePaintPropsPossiblyEvaluated} from './line_style_layer_properties.g';\nimport {extend} from '../../util/util';\nimport {EvaluationParameters} from '../evaluation_parameters';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated, DataDrivenProperty} from '../properties';\n\nimport {isZoomExpression, Step} from '@maplibre/maplibre-gl-style-spec';\nimport type {FeatureState, LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Bucket, BucketParameters} from '../../data/bucket';\nimport type {LineLayoutProps, LinePaintProps} from './line_style_layer_properties.g';\nimport type {Transform} from '../../geo/transform';\nimport type {VectorTileFeature} from '@mapbox/vector-tile';\n\nexport class LineFloorwidthProperty extends DataDrivenProperty {\n useIntegerZoom: true;\n\n possiblyEvaluate(value, parameters) {\n parameters = new EvaluationParameters(Math.floor(parameters.zoom), {\n now: parameters.now,\n fadeDuration: parameters.fadeDuration,\n zoomHistory: parameters.zoomHistory,\n transition: parameters.transition\n });\n return super.possiblyEvaluate(value, parameters);\n }\n\n evaluate(value, globals, feature, featureState) {\n globals = extend({}, globals, {zoom: Math.floor(globals.zoom)});\n return super.evaluate(value, globals, feature, featureState);\n }\n}\n\nlet lineFloorwidthProperty: LineFloorwidthProperty;\n\nexport class LineStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout;\n layout: PossiblyEvaluated;\n\n gradientVersion: number;\n stepInterpolant: boolean;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n this.gradientVersion = 0;\n if (!lineFloorwidthProperty) {\n lineFloorwidthProperty =\n new LineFloorwidthProperty(properties.paint.properties['line-width'].specification);\n lineFloorwidthProperty.useIntegerZoom = true;\n }\n }\n\n _handleSpecialPaintPropertyUpdate(name: string) {\n if (name === 'line-gradient') {\n const expression = this.gradientExpression();\n if (isZoomExpression(expression)) {\n this.stepInterpolant = expression._styleExpression.expression instanceof Step;\n } else {\n this.stepInterpolant = false;\n }\n this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER;\n }\n }\n\n gradientExpression() {\n return this._transitionablePaint._values['line-gradient'].value.expression;\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array) {\n super.recalculate(parameters, availableImages);\n (this.paint._values as any)['line-floorwidth'] =\n lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters);\n }\n\n createBucket(parameters: BucketParameters) {\n return new LineBucket(parameters);\n }\n\n queryRadius(bucket: Bucket): number {\n const lineBucket: LineBucket = (bucket as any);\n const width = getLineWidth(\n getMaximumPaintValue('line-width', this, lineBucket),\n getMaximumPaintValue('line-gap-width', this, lineBucket));\n const offset = getMaximumPaintValue('line-offset', this, lineBucket);\n return width / 2 + Math.abs(offset) + translateDistance(this.paint.get('line-translate'));\n }\n\n queryIntersectsFeature(\n queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number\n ): boolean {\n const translatedPolygon = translate(queryGeometry,\n this.paint.get('line-translate'),\n this.paint.get('line-translate-anchor'),\n transform.angle, pixelsToTileUnits);\n const halfWidth = pixelsToTileUnits / 2 * getLineWidth(\n this.paint.get('line-width').evaluate(feature, featureState),\n this.paint.get('line-gap-width').evaluate(feature, featureState));\n const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState);\n if (lineOffset) {\n geometry = offsetLine(geometry, lineOffset * pixelsToTileUnits);\n }\n\n return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth);\n }\n\n isTileClipped() {\n return true;\n }\n}\n\nfunction getLineWidth(lineWidth, lineGapWidth) {\n if (lineGapWidth > 0) {\n return lineGapWidth + 2 * lineWidth;\n } else {\n return lineWidth;\n }\n}\n","import {createLayout} from '../../util/struct_array';\n\nexport const symbolLayoutAttributes = createLayout([\n {name: 'a_pos_offset', components: 4, type: 'Int16'},\n {name: 'a_data', components: 4, type: 'Uint16'},\n {name: 'a_pixeloffset', components: 4, type: 'Int16'}\n], 4);\n\nexport const dynamicLayoutAttributes = createLayout([\n {name: 'a_projected_pos', components: 3, type: 'Float32'}\n], 4);\n\nexport const placementOpacityAttributes = createLayout([\n {name: 'a_fade_opacity', components: 1, type: 'Uint32'}\n], 4);\n\nexport const collisionVertexAttributes = createLayout([\n {name: 'a_placed', components: 2, type: 'Uint8'},\n {name: 'a_shift', components: 2, type: 'Float32'},\n {name: 'a_box_real', components: 2, type: 'Int16'},\n]);\n\nexport const collisionBox = createLayout([\n // the box is centered around the anchor point\n {type: 'Int16', name: 'anchorPointX'},\n {type: 'Int16', name: 'anchorPointY'},\n\n // distances to the edges from the anchor\n {type: 'Int16', name: 'x1'},\n {type: 'Int16', name: 'y1'},\n {type: 'Int16', name: 'x2'},\n {type: 'Int16', name: 'y2'},\n\n // the index of the feature in the original vectortile\n {type: 'Uint32', name: 'featureIndex'},\n // the source layer the feature appears in\n {type: 'Uint16', name: 'sourceLayerIndex'},\n // the bucket the feature appears in\n {type: 'Uint16', name: 'bucketIndex'},\n]);\n\nexport const collisionBoxLayout = createLayout([ // used to render collision boxes for debugging purposes\n {name: 'a_pos', components: 2, type: 'Int16'},\n {name: 'a_anchor_pos', components: 2, type: 'Int16'},\n {name: 'a_extrude', components: 2, type: 'Int16'}\n], 4);\n\nexport const collisionCircleLayout = createLayout([ // used to render collision circles for debugging purposes\n {name: 'a_pos', components: 2, type: 'Float32'},\n {name: 'a_radius', components: 1, type: 'Float32'},\n {name: 'a_flags', components: 2, type: 'Int16'}\n], 4);\n\nexport const quadTriangle = createLayout([\n {name: 'triangle', components: 3, type: 'Uint16'},\n]);\n\nexport const placement = createLayout([\n {type: 'Int16', name: 'anchorX'},\n {type: 'Int16', name: 'anchorY'},\n {type: 'Uint16', name: 'glyphStartIndex'},\n {type: 'Uint16', name: 'numGlyphs'},\n {type: 'Uint32', name: 'vertexStartIndex'},\n {type: 'Uint32', name: 'lineStartIndex'},\n {type: 'Uint32', name: 'lineLength'},\n {type: 'Uint16', name: 'segment'},\n {type: 'Uint16', name: 'lowerSize'},\n {type: 'Uint16', name: 'upperSize'},\n {type: 'Float32', name: 'lineOffsetX'},\n {type: 'Float32', name: 'lineOffsetY'},\n {type: 'Uint8', name: 'writingMode'},\n {type: 'Uint8', name: 'placedOrientation'},\n {type: 'Uint8', name: 'hidden'},\n {type: 'Uint32', name: 'crossTileID'},\n {type: 'Int16', name: 'associatedIconIndex'}\n]);\n\nexport const symbolInstance = createLayout([\n {type: 'Int16', name: 'anchorX'},\n {type: 'Int16', name: 'anchorY'},\n {type: 'Int16', name: 'rightJustifiedTextSymbolIndex'},\n {type: 'Int16', name: 'centerJustifiedTextSymbolIndex'},\n {type: 'Int16', name: 'leftJustifiedTextSymbolIndex'},\n {type: 'Int16', name: 'verticalPlacedTextSymbolIndex'},\n {type: 'Int16', name: 'placedIconSymbolIndex'},\n {type: 'Int16', name: 'verticalPlacedIconSymbolIndex'},\n {type: 'Uint16', name: 'key'},\n {type: 'Uint16', name: 'textBoxStartIndex'},\n {type: 'Uint16', name: 'textBoxEndIndex'},\n {type: 'Uint16', name: 'verticalTextBoxStartIndex'},\n {type: 'Uint16', name: 'verticalTextBoxEndIndex'},\n {type: 'Uint16', name: 'iconBoxStartIndex'},\n {type: 'Uint16', name: 'iconBoxEndIndex'},\n {type: 'Uint16', name: 'verticalIconBoxStartIndex'},\n {type: 'Uint16', name: 'verticalIconBoxEndIndex'},\n {type: 'Uint16', name: 'featureIndex'},\n {type: 'Uint16', name: 'numHorizontalGlyphVertices'},\n {type: 'Uint16', name: 'numVerticalGlyphVertices'},\n {type: 'Uint16', name: 'numIconVertices'},\n {type: 'Uint16', name: 'numVerticalIconVertices'},\n {type: 'Uint16', name: 'useRuntimeCollisionCircles'},\n {type: 'Uint32', name: 'crossTileID'},\n {type: 'Float32', name: 'textBoxScale'},\n {type: 'Float32', name: 'collisionCircleDiameter'},\n {type: 'Uint16', name: 'textAnchorOffsetStartIndex'},\n {type: 'Uint16', name: 'textAnchorOffsetEndIndex'}\n]);\n\nexport const glyphOffset = createLayout([\n {type: 'Float32', name: 'offsetX'}\n]);\n\nexport const lineVertex = createLayout([\n {type: 'Int16', name: 'x'},\n {type: 'Int16', name: 'y'},\n {type: 'Int16', name: 'tileUnitDistanceFromAnchor'}\n]);\n\nexport const textAnchorOffset = createLayout([\n {type: 'Uint16', name: 'textAnchor'},\n {type: 'Float32', components: 2, name: 'textOffset'}\n]);\n","import {rtlWorkerPlugin} from '../source/rtl_text_plugin_worker';\n\nimport type {SymbolStyleLayer} from '../style/style_layer/symbol_style_layer';\nimport type {Feature} from '@maplibre/maplibre-gl-style-spec';\nimport {Formatted} from '@maplibre/maplibre-gl-style-spec';\n\nfunction transformTextInternal(text: string, layer: SymbolStyleLayer, feature: Feature) {\n const transform = layer.layout.get('text-transform').evaluate(feature, {});\n if (transform === 'uppercase') {\n text = text.toLocaleUpperCase();\n } else if (transform === 'lowercase') {\n text = text.toLocaleLowerCase();\n }\n\n if (rtlWorkerPlugin.applyArabicShaping) {\n text = rtlWorkerPlugin.applyArabicShaping(text);\n }\n\n return text;\n}\n\nexport function transformText(text: Formatted, layer: SymbolStyleLayer, feature: Feature): Formatted {\n text.sections.forEach(section => {\n section.text = transformTextInternal(section.text, layer, feature);\n });\n return text;\n}\n","import {charHasRotatedVerticalOrientation} from './script_detection';\n\nexport const verticalizedCharacterMap = {\n '!': '︕',\n '#': '#',\n '$': '$',\n '%': '%',\n '&': '&',\n '(': '︵',\n ')': '︶',\n '*': '*',\n '+': '+',\n ',': '︐',\n '-': '︲',\n '.': '・',\n '/': '/',\n ':': '︓',\n ';': '︔',\n '<': '︿',\n '=': '=',\n '>': '﹀',\n '?': '︖',\n '@': '@',\n '[': '﹇',\n '\\\\': '\',\n ']': '﹈',\n '^': '^',\n '_': '︳',\n '`': '`',\n '{': '︷',\n '|': '―',\n '}': '︸',\n '~': '~',\n '¢': '¢',\n '£': '£',\n '¥': '¥',\n '¦': '¦',\n '¬': '¬',\n '¯': ' ̄',\n '–': '︲',\n '—': '︱',\n '‘': '﹃',\n '’': '﹄',\n '“': '﹁',\n '”': '﹂',\n '…': '︙',\n '‧': '・',\n '₩': '₩',\n '、': '︑',\n '。': '︒',\n '〈': '︿',\n '〉': '﹀',\n '《': '︽',\n '》': '︾',\n '「': '﹁',\n '」': '﹂',\n '『': '﹃',\n '』': '﹄',\n '【': '︻',\n '】': '︼',\n '〔': '︹',\n '〕': '︺',\n '〖': '︗',\n '〗': '︘',\n '!': '︕',\n '(': '︵',\n ')': '︶',\n ',': '︐',\n '-': '︲',\n '.': '・',\n ':': '︓',\n ';': '︔',\n '<': '︿',\n '>': '﹀',\n '?': '︖',\n '[': '﹇',\n ']': '﹈',\n '_': '︳',\n '{': '︷',\n '|': '―',\n '}': '︸',\n '⦅': '︵',\n '⦆': '︶',\n '。': '︒',\n '「': '﹁',\n '」': '﹂'\n};\n\nexport function verticalizePunctuation(input: string) {\n let output = '';\n\n for (let i = 0; i < input.length; i++) {\n const nextCharCode = input.charCodeAt(i + 1) || null;\n const prevCharCode = input.charCodeAt(i - 1) || null;\n\n const canReplacePunctuation = (\n (!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) &&\n (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]])\n );\n\n if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) {\n output += verticalizedCharacterMap[input[i]];\n } else {\n output += input[i];\n }\n }\n\n return output;\n}\n\n","// ONE_EM constant used to go between \"em\" units used in style spec and \"points\" used internally for layout\n\nexport default 24;\n","'use strict';\n\nmodule.exports = Pbf;\n\nvar ieee754 = require('ieee754');\n\nfunction Pbf(buf) {\n this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);\n this.pos = 0;\n this.type = 0;\n this.length = this.buf.length;\n}\n\nPbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum\nPbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64\nPbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields\nPbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32\n\nvar SHIFT_LEFT_32 = (1 << 16) * (1 << 16),\n SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;\n\n// Threshold chosen based on both benchmarking and knowledge about browser string\n// data structures (which currently switch structure types at 12 bytes or more)\nvar TEXT_DECODER_MIN_LENGTH = 12;\nvar utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8');\n\nPbf.prototype = {\n\n destroy: function() {\n this.buf = null;\n },\n\n // === READING =================================================================\n\n readFields: function(readField, result, end) {\n end = end || this.length;\n\n while (this.pos < end) {\n var val = this.readVarint(),\n tag = val >> 3,\n startPos = this.pos;\n\n this.type = val & 0x7;\n readField(tag, result, this);\n\n if (this.pos === startPos) this.skip(val);\n }\n return result;\n },\n\n readMessage: function(readField, result) {\n return this.readFields(readField, result, this.readVarint() + this.pos);\n },\n\n readFixed32: function() {\n var val = readUInt32(this.buf, this.pos);\n this.pos += 4;\n return val;\n },\n\n readSFixed32: function() {\n var val = readInt32(this.buf, this.pos);\n this.pos += 4;\n return val;\n },\n\n // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)\n\n readFixed64: function() {\n var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;\n this.pos += 8;\n return val;\n },\n\n readSFixed64: function() {\n var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;\n this.pos += 8;\n return val;\n },\n\n readFloat: function() {\n var val = ieee754.read(this.buf, this.pos, true, 23, 4);\n this.pos += 4;\n return val;\n },\n\n readDouble: function() {\n var val = ieee754.read(this.buf, this.pos, true, 52, 8);\n this.pos += 8;\n return val;\n },\n\n readVarint: function(isSigned) {\n var buf = this.buf,\n val, b;\n\n b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val;\n b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val;\n b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;\n b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;\n b = buf[this.pos]; val |= (b & 0x0f) << 28;\n\n return readVarintRemainder(val, isSigned, this);\n },\n\n readVarint64: function() { // for compatibility with v2.0.1\n return this.readVarint(true);\n },\n\n readSVarint: function() {\n var num = this.readVarint();\n return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding\n },\n\n readBoolean: function() {\n return Boolean(this.readVarint());\n },\n\n readString: function() {\n var end = this.readVarint() + this.pos;\n var pos = this.pos;\n this.pos = end;\n\n if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) {\n // longer strings are fast with the built-in browser TextDecoder API\n return readUtf8TextDecoder(this.buf, pos, end);\n }\n // short strings are fast with our custom implementation\n return readUtf8(this.buf, pos, end);\n },\n\n readBytes: function() {\n var end = this.readVarint() + this.pos,\n buffer = this.buf.subarray(this.pos, end);\n this.pos = end;\n return buffer;\n },\n\n // verbose for performance reasons; doesn't affect gzipped size\n\n readPackedVarint: function(arr, isSigned) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned));\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readVarint(isSigned));\n return arr;\n },\n readPackedSVarint: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readSVarint());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readSVarint());\n return arr;\n },\n readPackedBoolean: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readBoolean());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readBoolean());\n return arr;\n },\n readPackedFloat: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readFloat());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readFloat());\n return arr;\n },\n readPackedDouble: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readDouble());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readDouble());\n return arr;\n },\n readPackedFixed32: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readFixed32());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readFixed32());\n return arr;\n },\n readPackedSFixed32: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed32());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readSFixed32());\n return arr;\n },\n readPackedFixed64: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readFixed64());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readFixed64());\n return arr;\n },\n readPackedSFixed64: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed64());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readSFixed64());\n return arr;\n },\n\n skip: function(val) {\n var type = val & 0x7;\n if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}\n else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;\n else if (type === Pbf.Fixed32) this.pos += 4;\n else if (type === Pbf.Fixed64) this.pos += 8;\n else throw new Error('Unimplemented type: ' + type);\n },\n\n // === WRITING =================================================================\n\n writeTag: function(tag, type) {\n this.writeVarint((tag << 3) | type);\n },\n\n realloc: function(min) {\n var length = this.length || 16;\n\n while (length < this.pos + min) length *= 2;\n\n if (length !== this.length) {\n var buf = new Uint8Array(length);\n buf.set(this.buf);\n this.buf = buf;\n this.length = length;\n }\n },\n\n finish: function() {\n this.length = this.pos;\n this.pos = 0;\n return this.buf.subarray(0, this.length);\n },\n\n writeFixed32: function(val) {\n this.realloc(4);\n writeInt32(this.buf, val, this.pos);\n this.pos += 4;\n },\n\n writeSFixed32: function(val) {\n this.realloc(4);\n writeInt32(this.buf, val, this.pos);\n this.pos += 4;\n },\n\n writeFixed64: function(val) {\n this.realloc(8);\n writeInt32(this.buf, val & -1, this.pos);\n writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);\n this.pos += 8;\n },\n\n writeSFixed64: function(val) {\n this.realloc(8);\n writeInt32(this.buf, val & -1, this.pos);\n writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);\n this.pos += 8;\n },\n\n writeVarint: function(val) {\n val = +val || 0;\n\n if (val > 0xfffffff || val < 0) {\n writeBigVarint(val, this);\n return;\n }\n\n this.realloc(4);\n\n this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;\n this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;\n this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;\n this.buf[this.pos++] = (val >>> 7) & 0x7f;\n },\n\n writeSVarint: function(val) {\n this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);\n },\n\n writeBoolean: function(val) {\n this.writeVarint(Boolean(val));\n },\n\n writeString: function(str) {\n str = String(str);\n this.realloc(str.length * 4);\n\n this.pos++; // reserve 1 byte for short string length\n\n var startPos = this.pos;\n // write the string directly to the buffer and see how much was written\n this.pos = writeUtf8(this.buf, str, this.pos);\n var len = this.pos - startPos;\n\n if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);\n\n // finally, write the message length in the reserved place and restore the position\n this.pos = startPos - 1;\n this.writeVarint(len);\n this.pos += len;\n },\n\n writeFloat: function(val) {\n this.realloc(4);\n ieee754.write(this.buf, val, this.pos, true, 23, 4);\n this.pos += 4;\n },\n\n writeDouble: function(val) {\n this.realloc(8);\n ieee754.write(this.buf, val, this.pos, true, 52, 8);\n this.pos += 8;\n },\n\n writeBytes: function(buffer) {\n var len = buffer.length;\n this.writeVarint(len);\n this.realloc(len);\n for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];\n },\n\n writeRawMessage: function(fn, obj) {\n this.pos++; // reserve 1 byte for short message length\n\n // write the message directly to the buffer and see how much was written\n var startPos = this.pos;\n fn(obj, this);\n var len = this.pos - startPos;\n\n if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);\n\n // finally, write the message length in the reserved place and restore the position\n this.pos = startPos - 1;\n this.writeVarint(len);\n this.pos += len;\n },\n\n writeMessage: function(tag, fn, obj) {\n this.writeTag(tag, Pbf.Bytes);\n this.writeRawMessage(fn, obj);\n },\n\n writePackedVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedVarint, arr); },\n writePackedSVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); },\n writePackedBoolean: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); },\n writePackedFloat: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFloat, arr); },\n writePackedDouble: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedDouble, arr); },\n writePackedFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); },\n writePackedSFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); },\n writePackedFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); },\n writePackedSFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); },\n\n writeBytesField: function(tag, buffer) {\n this.writeTag(tag, Pbf.Bytes);\n this.writeBytes(buffer);\n },\n writeFixed32Field: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed32);\n this.writeFixed32(val);\n },\n writeSFixed32Field: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed32);\n this.writeSFixed32(val);\n },\n writeFixed64Field: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed64);\n this.writeFixed64(val);\n },\n writeSFixed64Field: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed64);\n this.writeSFixed64(val);\n },\n writeVarintField: function(tag, val) {\n this.writeTag(tag, Pbf.Varint);\n this.writeVarint(val);\n },\n writeSVarintField: function(tag, val) {\n this.writeTag(tag, Pbf.Varint);\n this.writeSVarint(val);\n },\n writeStringField: function(tag, str) {\n this.writeTag(tag, Pbf.Bytes);\n this.writeString(str);\n },\n writeFloatField: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed32);\n this.writeFloat(val);\n },\n writeDoubleField: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed64);\n this.writeDouble(val);\n },\n writeBooleanField: function(tag, val) {\n this.writeVarintField(tag, Boolean(val));\n }\n};\n\nfunction readVarintRemainder(l, s, p) {\n var buf = p.buf,\n h, b;\n\n b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);\n\n throw new Error('Expected varint not more than 10 bytes');\n}\n\nfunction readPackedEnd(pbf) {\n return pbf.type === Pbf.Bytes ?\n pbf.readVarint() + pbf.pos : pbf.pos + 1;\n}\n\nfunction toNum(low, high, isSigned) {\n if (isSigned) {\n return high * 0x100000000 + (low >>> 0);\n }\n\n return ((high >>> 0) * 0x100000000) + (low >>> 0);\n}\n\nfunction writeBigVarint(val, pbf) {\n var low, high;\n\n if (val >= 0) {\n low = (val % 0x100000000) | 0;\n high = (val / 0x100000000) | 0;\n } else {\n low = ~(-val % 0x100000000);\n high = ~(-val / 0x100000000);\n\n if (low ^ 0xffffffff) {\n low = (low + 1) | 0;\n } else {\n low = 0;\n high = (high + 1) | 0;\n }\n }\n\n if (val >= 0x10000000000000000 || val < -0x10000000000000000) {\n throw new Error('Given varint doesn\\'t fit into 10 bytes');\n }\n\n pbf.realloc(10);\n\n writeBigVarintLow(low, high, pbf);\n writeBigVarintHigh(high, pbf);\n}\n\nfunction writeBigVarintLow(low, high, pbf) {\n pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n pbf.buf[pbf.pos] = low & 0x7f;\n}\n\nfunction writeBigVarintHigh(high, pbf) {\n var lsb = (high & 0x07) << 4;\n\n pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f;\n}\n\nfunction makeRoomForExtraLength(startPos, len, pbf) {\n var extraLen =\n len <= 0x3fff ? 1 :\n len <= 0x1fffff ? 2 :\n len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7));\n\n // if 1 byte isn't enough for encoding message length, shift the data to the right\n pbf.realloc(extraLen);\n for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];\n}\n\nfunction writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); }\nfunction writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); }\nfunction writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); }\nfunction writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); }\nfunction writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); }\nfunction writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); }\nfunction writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }\nfunction writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); }\nfunction writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }\n\n// Buffer code below from https://github.com/feross/buffer, MIT-licensed\n\nfunction readUInt32(buf, pos) {\n return ((buf[pos]) |\n (buf[pos + 1] << 8) |\n (buf[pos + 2] << 16)) +\n (buf[pos + 3] * 0x1000000);\n}\n\nfunction writeInt32(buf, val, pos) {\n buf[pos] = val;\n buf[pos + 1] = (val >>> 8);\n buf[pos + 2] = (val >>> 16);\n buf[pos + 3] = (val >>> 24);\n}\n\nfunction readInt32(buf, pos) {\n return ((buf[pos]) |\n (buf[pos + 1] << 8) |\n (buf[pos + 2] << 16)) +\n (buf[pos + 3] << 24);\n}\n\nfunction readUtf8(buf, pos, end) {\n var str = '';\n var i = pos;\n\n while (i < end) {\n var b0 = buf[i];\n var c = null; // codepoint\n var bytesPerSequence =\n b0 > 0xEF ? 4 :\n b0 > 0xDF ? 3 :\n b0 > 0xBF ? 2 : 1;\n\n if (i + bytesPerSequence > end) break;\n\n var b1, b2, b3;\n\n if (bytesPerSequence === 1) {\n if (b0 < 0x80) {\n c = b0;\n }\n } else if (bytesPerSequence === 2) {\n b1 = buf[i + 1];\n if ((b1 & 0xC0) === 0x80) {\n c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);\n if (c <= 0x7F) {\n c = null;\n }\n }\n } else if (bytesPerSequence === 3) {\n b1 = buf[i + 1];\n b2 = buf[i + 2];\n if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {\n c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);\n if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {\n c = null;\n }\n }\n } else if (bytesPerSequence === 4) {\n b1 = buf[i + 1];\n b2 = buf[i + 2];\n b3 = buf[i + 3];\n if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {\n c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);\n if (c <= 0xFFFF || c >= 0x110000) {\n c = null;\n }\n }\n }\n\n if (c === null) {\n c = 0xFFFD;\n bytesPerSequence = 1;\n\n } else if (c > 0xFFFF) {\n c -= 0x10000;\n str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);\n c = 0xDC00 | c & 0x3FF;\n }\n\n str += String.fromCharCode(c);\n i += bytesPerSequence;\n }\n\n return str;\n}\n\nfunction readUtf8TextDecoder(buf, pos, end) {\n return utf8TextDecoder.decode(buf.subarray(pos, end));\n}\n\nfunction writeUtf8(buf, str, pos) {\n for (var i = 0, c, lead; i < str.length; i++) {\n c = str.charCodeAt(i); // code point\n\n if (c > 0xD7FF && c < 0xE000) {\n if (lead) {\n if (c < 0xDC00) {\n buf[pos++] = 0xEF;\n buf[pos++] = 0xBF;\n buf[pos++] = 0xBD;\n lead = c;\n continue;\n } else {\n c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;\n lead = null;\n }\n } else {\n if (c > 0xDBFF || (i + 1 === str.length)) {\n buf[pos++] = 0xEF;\n buf[pos++] = 0xBF;\n buf[pos++] = 0xBD;\n } else {\n lead = c;\n }\n continue;\n }\n } else if (lead) {\n buf[pos++] = 0xEF;\n buf[pos++] = 0xBF;\n buf[pos++] = 0xBD;\n lead = null;\n }\n\n if (c < 0x80) {\n buf[pos++] = c;\n } else {\n if (c < 0x800) {\n buf[pos++] = c >> 0x6 | 0xC0;\n } else {\n if (c < 0x10000) {\n buf[pos++] = c >> 0xC | 0xE0;\n } else {\n buf[pos++] = c >> 0x12 | 0xF0;\n buf[pos++] = c >> 0xC & 0x3F | 0x80;\n }\n buf[pos++] = c >> 0x6 & 0x3F | 0x80;\n }\n buf[pos++] = c & 0x3F | 0x80;\n }\n }\n return pos;\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","import {AlphaImage} from '../util/image';\n\nimport Protobuf from 'pbf';\nconst border = 3;\n\nimport type {StyleGlyph} from './style_glyph';\n\nfunction readFontstacks(tag: number, glyphs: Array, pbf: Protobuf) {\n if (tag === 1) {\n pbf.readMessage(readFontstack, glyphs);\n }\n}\n\nfunction readFontstack(tag: number, glyphs: Array, pbf: Protobuf) {\n if (tag === 3) {\n const {id, bitmap, width, height, left, top, advance} = pbf.readMessage(readGlyph, {});\n glyphs.push({\n id,\n bitmap: new AlphaImage({\n width: width + 2 * border,\n height: height + 2 * border\n }, bitmap),\n metrics: {width, height, left, top, advance}\n });\n }\n}\n\nfunction readGlyph(tag: number, glyph: any, pbf: Protobuf) {\n if (tag === 1) glyph.id = pbf.readVarint();\n else if (tag === 2) glyph.bitmap = pbf.readBytes();\n else if (tag === 3) glyph.width = pbf.readVarint();\n else if (tag === 4) glyph.height = pbf.readVarint();\n else if (tag === 5) glyph.left = pbf.readSVarint();\n else if (tag === 6) glyph.top = pbf.readSVarint();\n else if (tag === 7) glyph.advance = pbf.readVarint();\n}\n\nexport function parseGlyphPbf(data: ArrayBuffer | Uint8Array): Array {\n return new Protobuf(data).readFields(readFontstacks, []);\n}\n\nexport const GLYPH_PBF_BORDER = border;\n","\nexport default function potpack(boxes) {\n\n // calculate total box area and maximum box width\n let area = 0;\n let maxWidth = 0;\n\n for (const box of boxes) {\n area += box.w * box.h;\n maxWidth = Math.max(maxWidth, box.w);\n }\n\n // sort the boxes for insertion by height, descending\n boxes.sort((a, b) => b.h - a.h);\n\n // aim for a squarish resulting container,\n // slightly adjusted for sub-100% space utilization\n const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth);\n\n // start with a single empty space, unbounded at the bottom\n const spaces = [{x: 0, y: 0, w: startWidth, h: Infinity}];\n\n let width = 0;\n let height = 0;\n\n for (const box of boxes) {\n // look through spaces backwards so that we check smaller spaces first\n for (let i = spaces.length - 1; i >= 0; i--) {\n const space = spaces[i];\n\n // look for empty spaces that can accommodate the current box\n if (box.w > space.w || box.h > space.h) continue;\n\n // found the space; add the box to its top-left corner\n // |-------|-------|\n // | box | |\n // |_______| |\n // | space |\n // |_______________|\n box.x = space.x;\n box.y = space.y;\n\n height = Math.max(height, box.y + box.h);\n width = Math.max(width, box.x + box.w);\n\n if (box.w === space.w && box.h === space.h) {\n // space matches the box exactly; remove it\n const last = spaces.pop();\n if (i < spaces.length) spaces[i] = last;\n\n } else if (box.h === space.h) {\n // space matches the box height; update it accordingly\n // |-------|---------------|\n // | box | updated space |\n // |_______|_______________|\n space.x += box.w;\n space.w -= box.w;\n\n } else if (box.w === space.w) {\n // space matches the box width; update it accordingly\n // |---------------|\n // | box |\n // |_______________|\n // | updated space |\n // |_______________|\n space.y += box.h;\n space.h -= box.h;\n\n } else {\n // otherwise the box splits the space into two spaces\n // |-------|-----------|\n // | box | new space |\n // |_______|___________|\n // | updated space |\n // |___________________|\n spaces.push({\n x: space.x + box.w,\n y: space.y,\n w: space.w - box.w,\n h: box.h\n });\n space.y += box.h;\n space.h -= box.h;\n }\n break;\n }\n }\n\n return {\n w: width, // container width\n h: height, // container height\n fill: (area / (width * height)) || 0 // space utilization\n };\n}\n","/* eslint-disable key-spacing */\nimport {RGBAImage} from '../util/image';\nimport {register} from '../util/web_worker_transfer';\nimport potpack from 'potpack';\n\nimport type {StyleImage} from '../style/style_image';\nimport {TextFit} from '../style/style_image';\nimport type {ImageManager} from './image_manager';\nimport type {Texture} from './texture';\nimport type {Rect} from './glyph_atlas';\nimport type {GetImagesResponse} from '../util/actor_messages';\n\nconst IMAGE_PADDING: number = 1;\nexport {IMAGE_PADDING};\n\nexport class ImagePosition {\n paddedRect: Rect;\n pixelRatio: number;\n version: number;\n stretchY: Array<[number, number]>;\n stretchX: Array<[number, number]>;\n content: [number, number, number, number];\n textFitWidth: TextFit;\n textFitHeight: TextFit;\n\n constructor(paddedRect: Rect, {\n pixelRatio,\n version,\n stretchX,\n stretchY,\n content,\n textFitWidth,\n textFitHeight\n }: StyleImage) {\n this.paddedRect = paddedRect;\n this.pixelRatio = pixelRatio;\n this.stretchX = stretchX;\n this.stretchY = stretchY;\n this.content = content;\n this.version = version;\n this.textFitWidth = textFitWidth;\n this.textFitHeight = textFitHeight;\n }\n\n get tl(): [number, number] {\n return [\n this.paddedRect.x + IMAGE_PADDING,\n this.paddedRect.y + IMAGE_PADDING\n ];\n }\n\n get br(): [number, number] {\n return [\n this.paddedRect.x + this.paddedRect.w - IMAGE_PADDING,\n this.paddedRect.y + this.paddedRect.h - IMAGE_PADDING\n ];\n }\n\n get tlbr(): Array {\n return this.tl.concat(this.br);\n }\n\n get displaySize(): [number, number] {\n return [\n (this.paddedRect.w - IMAGE_PADDING * 2) / this.pixelRatio,\n (this.paddedRect.h - IMAGE_PADDING * 2) / this.pixelRatio\n ];\n }\n}\n\n/**\n * A class holding all the images\n */\nexport class ImageAtlas {\n image: RGBAImage;\n iconPositions: {[_: string]: ImagePosition};\n patternPositions: {[_: string]: ImagePosition};\n haveRenderCallbacks: Array;\n uploaded: boolean;\n\n constructor(icons: GetImagesResponse, patterns: GetImagesResponse) {\n const iconPositions = {}, patternPositions = {};\n this.haveRenderCallbacks = [];\n\n const bins = [];\n\n this.addImages(icons, iconPositions, bins);\n this.addImages(patterns, patternPositions, bins);\n\n const {w, h} = potpack(bins);\n const image = new RGBAImage({width: w || 1, height: h || 1});\n\n for (const id in icons) {\n const src = icons[id];\n const bin = iconPositions[id].paddedRect;\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x: bin.x + IMAGE_PADDING, y: bin.y + IMAGE_PADDING}, src.data);\n }\n\n for (const id in patterns) {\n const src = patterns[id];\n const bin = patternPositions[id].paddedRect;\n const x = bin.x + IMAGE_PADDING,\n y = bin.y + IMAGE_PADDING,\n w = src.data.width,\n h = src.data.height;\n\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x, y}, src.data);\n // Add 1 pixel wrapped padding on each side of the image.\n RGBAImage.copy(src.data, image, {x: 0, y: h - 1}, {x, y: y - 1}, {width: w, height: 1}); // T\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x, y: y + h}, {width: w, height: 1}); // B\n RGBAImage.copy(src.data, image, {x: w - 1, y: 0}, {x: x - 1, y}, {width: 1, height: h}); // L\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x: x + w, y}, {width: 1, height: h}); // R\n }\n\n this.image = image;\n this.iconPositions = iconPositions;\n this.patternPositions = patternPositions;\n }\n\n addImages(images: {[_: string]: StyleImage}, positions: {[_: string]: ImagePosition}, bins: Array) {\n for (const id in images) {\n const src = images[id];\n const bin = {\n x: 0,\n y: 0,\n w: src.data.width + 2 * IMAGE_PADDING,\n h: src.data.height + 2 * IMAGE_PADDING,\n };\n bins.push(bin);\n positions[id] = new ImagePosition(bin, src);\n\n if (src.hasRenderCallback) {\n this.haveRenderCallbacks.push(id);\n }\n }\n }\n\n patchUpdatedImages(imageManager: ImageManager, texture: Texture) {\n imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks);\n for (const name in imageManager.updatedImages) {\n this.patchUpdatedImage(this.iconPositions[name], imageManager.getImage(name), texture);\n this.patchUpdatedImage(this.patternPositions[name], imageManager.getImage(name), texture);\n }\n }\n\n patchUpdatedImage(position: ImagePosition, image: StyleImage, texture: Texture) {\n if (!position || !image) return;\n\n if (position.version === image.version) return;\n\n position.version = image.version;\n const [x, y] = position.tl;\n texture.update(image.data, undefined, {x, y});\n }\n\n}\n\nregister('ImagePosition', ImagePosition);\nregister('ImageAtlas', ImageAtlas);\n","import {\n charHasUprightVerticalOrientation,\n charAllowsIdeographicBreaking,\n charInComplexShapingScript\n} from '../util/script_detection';\nimport {verticalizePunctuation} from '../util/verticalize_punctuation';\nimport {rtlWorkerPlugin} from '../source/rtl_text_plugin_worker';\nimport ONE_EM from './one_em';\nimport {warnOnce} from '../util/util';\n\nimport type {StyleGlyph, GlyphMetrics} from '../style/style_glyph';\nimport {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf';\nimport {TextFit} from '../style/style_image';\nimport type {ImagePosition} from '../render/image_atlas';\nimport {IMAGE_PADDING} from '../render/image_atlas';\nimport type {Rect, GlyphPosition} from '../render/glyph_atlas';\nimport {Formatted, FormattedSection} from '@maplibre/maplibre-gl-style-spec';\n\nenum WritingMode {\n none = 0,\n horizontal = 1,\n vertical = 2,\n horizontalOnly = 3\n}\n\nconst SHAPING_DEFAULT_OFFSET = -17;\nexport {shapeText, shapeIcon, applyTextFit, fitIconToText, getAnchorAlignment, WritingMode, SHAPING_DEFAULT_OFFSET};\n\n// The position of a glyph relative to the text's anchor point.\nexport type PositionedGlyph = {\n glyph: number;\n imageName: string | null;\n x: number;\n y: number;\n vertical: boolean;\n scale: number;\n fontStack: string;\n sectionIndex: number;\n metrics: GlyphMetrics;\n rect: Rect | null;\n};\n\nexport type PositionedLine = {\n positionedGlyphs: Array;\n lineOffset: number;\n};\n\n// A collection of positioned glyphs and some metadata\nexport type Shaping = {\n positionedLines: Array;\n top: number;\n bottom: number;\n left: number;\n right: number;\n writingMode: WritingMode.horizontal | WritingMode.vertical;\n text: string;\n iconsInText: boolean;\n verticalizable: boolean;\n};\n\nfunction isEmpty(positionedLines: Array) {\n for (const line of positionedLines) {\n if (line.positionedGlyphs.length !== 0) {\n return false;\n }\n }\n return true;\n}\n\nexport type SymbolAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\nexport type TextJustify = 'left' | 'center' | 'right';\n\n// Max number of images in label is 6401 U+E000–U+F8FF that covers\n// Basic Multilingual Plane Unicode Private Use Area (PUA).\nconst PUAbegin = 0xE000;\nconst PUAend = 0xF8FF;\n\nclass SectionOptions {\n // Text options\n scale: number;\n fontStack: string;\n // Image options\n imageName: string | null;\n\n constructor() {\n this.scale = 1.0;\n this.fontStack = '';\n this.imageName = null;\n }\n\n static forText(scale: number | null, fontStack: string) {\n const textOptions = new SectionOptions();\n textOptions.scale = scale || 1;\n textOptions.fontStack = fontStack;\n return textOptions;\n }\n\n static forImage(imageName: string) {\n const imageOptions = new SectionOptions();\n imageOptions.imageName = imageName;\n return imageOptions;\n }\n\n}\n\nclass TaggedString {\n text: string;\n sectionIndex: Array; // maps each character in 'text' to its corresponding entry in 'sections'\n sections: Array;\n imageSectionID: number | null;\n\n constructor() {\n this.text = '';\n this.sectionIndex = [];\n this.sections = [];\n this.imageSectionID = null;\n }\n\n static fromFeature(text: Formatted, defaultFontStack: string) {\n const result = new TaggedString();\n for (let i = 0; i < text.sections.length; i++) {\n const section = text.sections[i];\n if (!section.image) {\n result.addTextSection(section, defaultFontStack);\n } else {\n result.addImageSection(section);\n }\n }\n return result;\n }\n\n length(): number {\n return this.text.length;\n }\n\n getSection(index: number): SectionOptions {\n return this.sections[this.sectionIndex[index]];\n }\n\n getSectionIndex(index: number): number {\n return this.sectionIndex[index];\n }\n\n getCharCode(index: number): number {\n return this.text.charCodeAt(index);\n }\n\n verticalizePunctuation() {\n this.text = verticalizePunctuation(this.text);\n }\n\n trim() {\n let beginningWhitespace = 0;\n for (let i = 0;\n i < this.text.length && whitespace[this.text.charCodeAt(i)];\n i++) {\n beginningWhitespace++;\n }\n let trailingWhitespace = this.text.length;\n for (let i = this.text.length - 1;\n i >= 0 && i >= beginningWhitespace && whitespace[this.text.charCodeAt(i)];\n i--) {\n trailingWhitespace--;\n }\n this.text = this.text.substring(beginningWhitespace, trailingWhitespace);\n this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace);\n }\n\n substring(start: number, end: number): TaggedString {\n const substring = new TaggedString();\n substring.text = this.text.substring(start, end);\n substring.sectionIndex = this.sectionIndex.slice(start, end);\n substring.sections = this.sections;\n return substring;\n }\n\n toString(): string {\n return this.text;\n }\n\n getMaxScale() {\n return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0);\n }\n\n addTextSection(section: FormattedSection, defaultFontStack: string) {\n this.text += section.text;\n this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack));\n const index = this.sections.length - 1;\n for (let i = 0; i < section.text.length; ++i) {\n this.sectionIndex.push(index);\n }\n }\n\n addImageSection(section: FormattedSection) {\n const imageName = section.image ? section.image.name : '';\n if (imageName.length === 0) {\n warnOnce('Can\\'t add FormattedSection with an empty image.');\n return;\n }\n\n const nextImageSectionCharCode = this.getNextImageSectionCharCode();\n if (!nextImageSectionCharCode) {\n warnOnce(`Reached maximum number of images ${PUAend - PUAbegin + 2}`);\n return;\n }\n\n this.text += String.fromCharCode(nextImageSectionCharCode);\n this.sections.push(SectionOptions.forImage(imageName));\n this.sectionIndex.push(this.sections.length - 1);\n }\n\n getNextImageSectionCharCode(): number | null {\n if (!this.imageSectionID) {\n this.imageSectionID = PUAbegin;\n return this.imageSectionID;\n }\n\n if (this.imageSectionID >= PUAend) return null;\n return ++this.imageSectionID;\n }\n}\n\nfunction breakLines(input: TaggedString, lineBreakPoints: Array): Array {\n const lines = [];\n const text = input.text;\n let start = 0;\n for (const lineBreak of lineBreakPoints) {\n lines.push(input.substring(start, lineBreak));\n start = lineBreak;\n }\n\n if (start < text.length) {\n lines.push(input.substring(start, text.length));\n }\n return lines;\n}\n\nfunction shapeText(\n text: Formatted,\n glyphMap: {\n [_: string]: {\n [_: number]: StyleGlyph;\n };\n },\n glyphPositions: {\n [_: string]: {\n [_: number]: GlyphPosition;\n };\n },\n imagePositions: {[_: string]: ImagePosition},\n defaultFontStack: string,\n maxWidth: number,\n lineHeight: number,\n textAnchor: SymbolAnchor,\n textJustify: TextJustify,\n spacing: number,\n translate: [number, number],\n writingMode: WritingMode.horizontal | WritingMode.vertical,\n allowVerticalPlacement: boolean,\n layoutTextSize: number,\n layoutTextSizeThisZoom: number\n): Shaping | false {\n const logicalInput = TaggedString.fromFeature(text, defaultFontStack);\n\n if (writingMode === WritingMode.vertical) {\n logicalInput.verticalizePunctuation();\n }\n\n let lines: Array;\n\n const {processBidirectionalText, processStyledBidirectionalText} = rtlWorkerPlugin;\n if (processBidirectionalText && logicalInput.sections.length === 1) {\n // Bidi doesn't have to be style-aware\n lines = [];\n const untaggedLines =\n processBidirectionalText(logicalInput.toString(),\n determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize));\n for (const line of untaggedLines) {\n const taggedLine = new TaggedString();\n taggedLine.text = line;\n taggedLine.sections = logicalInput.sections;\n for (let i = 0; i < line.length; i++) {\n taggedLine.sectionIndex.push(0);\n }\n lines.push(taggedLine);\n }\n } else if (processStyledBidirectionalText) {\n // Need version of mapbox-gl-rtl-text with style support for combining RTL text\n // with formatting\n lines = [];\n const processedLines =\n processStyledBidirectionalText(logicalInput.text,\n logicalInput.sectionIndex,\n determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize));\n for (const line of processedLines) {\n const taggedLine = new TaggedString();\n taggedLine.text = line[0];\n taggedLine.sectionIndex = line[1];\n taggedLine.sections = logicalInput.sections;\n lines.push(taggedLine);\n }\n } else {\n lines = breakLines(logicalInput, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize));\n }\n\n const positionedLines = [];\n const shaping = {\n positionedLines,\n text: logicalInput.toString(),\n top: translate[1],\n bottom: translate[1],\n left: translate[0],\n right: translate[0],\n writingMode,\n iconsInText: false,\n verticalizable: false\n };\n\n shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom);\n if (isEmpty(positionedLines)) return false;\n\n return shaping;\n}\n\n// using computed properties due to https://github.com/facebook/flow/issues/380\n/* eslint no-useless-computed-key: 0 */\n\nconst whitespace: {\n [_: number]: boolean;\n} = {\n [0x09]: true, // tab\n [0x0a]: true, // newline\n [0x0b]: true, // vertical tab\n [0x0c]: true, // form feed\n [0x0d]: true, // carriage return\n [0x20]: true, // space\n};\n\nconst breakable: {\n [_: number]: boolean;\n} = {\n [0x0a]: true, // newline\n [0x20]: true, // space\n [0x26]: true, // ampersand\n [0x29]: true, // right parenthesis\n [0x2b]: true, // plus sign\n [0x2d]: true, // hyphen-minus\n [0x2f]: true, // solidus\n [0xad]: true, // soft hyphen\n [0xb7]: true, // middle dot\n [0x200b]: true, // zero-width space\n [0x2010]: true, // hyphen\n [0x2013]: true, // en dash\n [0x2027]: true // interpunct\n // Many other characters may be reasonable breakpoints\n // Consider \"neutral orientation\" characters at scriptDetection.charHasNeutralVerticalOrientation\n // See https://github.com/mapbox/mapbox-gl-js/issues/3658\n};\n\n// Allow breaks depending on the following character\nconst breakableBefore: {\n [_: number]: boolean;\n} = {\n [0x28]: true, // left parenthesis\n};\n\nfunction getGlyphAdvance(\n codePoint: number,\n section: SectionOptions,\n glyphMap: {\n [_: string]: {\n [_: number]: StyleGlyph;\n };\n },\n imagePositions: {[_: string]: ImagePosition},\n spacing: number,\n layoutTextSize: number\n): number {\n if (!section.imageName) {\n const positions = glyphMap[section.fontStack];\n const glyph = positions && positions[codePoint];\n if (!glyph) return 0;\n return glyph.metrics.advance * section.scale + spacing;\n } else {\n const imagePosition = imagePositions[section.imageName];\n if (!imagePosition) return 0;\n return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing;\n }\n}\n\nfunction determineAverageLineWidth(logicalInput: TaggedString,\n spacing: number,\n maxWidth: number,\n glyphMap: {\n [_: string]: {\n [_: number]: StyleGlyph;\n };\n },\n imagePositions: {[_: string]: ImagePosition},\n layoutTextSize: number) {\n let totalWidth = 0;\n\n for (let index = 0; index < logicalInput.length(); index++) {\n const section = logicalInput.getSection(index);\n totalWidth += getGlyphAdvance(logicalInput.getCharCode(index), section, glyphMap, imagePositions, spacing, layoutTextSize);\n }\n\n const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth));\n return totalWidth / lineCount;\n}\n\nfunction calculateBadness(lineWidth: number,\n targetWidth: number,\n penalty: number,\n isLastBreak: boolean) {\n const raggedness = Math.pow(lineWidth - targetWidth, 2);\n if (isLastBreak) {\n // Favor finals lines shorter than average over longer than average\n if (lineWidth < targetWidth) {\n return raggedness / 2;\n } else {\n return raggedness * 2;\n }\n }\n\n return raggedness + Math.abs(penalty) * penalty;\n}\n\nfunction calculatePenalty(codePoint: number, nextCodePoint: number, penalizableIdeographicBreak: boolean) {\n let penalty = 0;\n // Force break on newline\n if (codePoint === 0x0a) {\n penalty -= 10000;\n }\n // Penalize breaks between characters that allow ideographic breaking because\n // they are less preferable than breaks at spaces (or zero width spaces).\n if (penalizableIdeographicBreak) {\n penalty += 150;\n }\n\n // Penalize open parenthesis at end of line\n if (codePoint === 0x28 || codePoint === 0xff08) {\n penalty += 50;\n }\n\n // Penalize close parenthesis at beginning of line\n if (nextCodePoint === 0x29 || nextCodePoint === 0xff09) {\n penalty += 50;\n }\n return penalty;\n}\n\ntype Break = {\n index: number;\n x: number;\n priorBreak: Break;\n badness: number;\n};\n\nfunction evaluateBreak(\n breakIndex: number,\n breakX: number,\n targetWidth: number,\n potentialBreaks: Array,\n penalty: number,\n isLastBreak: boolean\n): Break {\n // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth\n // ...but in fact we allow lines longer than maxWidth (if there's no break points)\n // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give\n // more lopsided results.\n\n let bestPriorBreak: Break = null;\n let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak);\n\n for (const potentialBreak of potentialBreaks) {\n const lineWidth = breakX - potentialBreak.x;\n const breakBadness =\n calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness;\n if (breakBadness <= bestBreakBadness) {\n bestPriorBreak = potentialBreak;\n bestBreakBadness = breakBadness;\n }\n }\n\n return {\n index: breakIndex,\n x: breakX,\n priorBreak: bestPriorBreak,\n badness: bestBreakBadness\n };\n}\n\nfunction leastBadBreaks(lastLineBreak?: Break | null): Array {\n if (!lastLineBreak) {\n return [];\n }\n return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index);\n}\n\nfunction determineLineBreaks(\n logicalInput: TaggedString,\n spacing: number,\n maxWidth: number,\n glyphMap: {\n [_: string]: {\n [_: number]: StyleGlyph;\n };\n },\n imagePositions: {[_: string]: ImagePosition},\n layoutTextSize: number\n): Array {\n if (!logicalInput)\n return [];\n\n const potentialLineBreaks = [];\n const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize);\n\n const hasServerSuggestedBreakpoints = logicalInput.text.indexOf('\\u200b') >= 0;\n\n let currentX = 0;\n\n for (let i = 0; i < logicalInput.length(); i++) {\n const section = logicalInput.getSection(i);\n const codePoint = logicalInput.getCharCode(i);\n if (!whitespace[codePoint]) currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize);\n\n // Ideographic characters, spaces, and word-breaking punctuation that often appear without\n // surrounding spaces.\n if ((i < logicalInput.length() - 1)) {\n const ideographicBreak = charAllowsIdeographicBreaking(codePoint);\n if (breakable[codePoint] || ideographicBreak || section.imageName || (i !== logicalInput.length() - 2 && breakableBefore[logicalInput.getCharCode(i + 1)])) {\n\n potentialLineBreaks.push(\n evaluateBreak(\n i + 1,\n currentX,\n targetWidth,\n potentialLineBreaks,\n calculatePenalty(codePoint, logicalInput.getCharCode(i + 1), ideographicBreak && hasServerSuggestedBreakpoints),\n false));\n }\n }\n }\n\n return leastBadBreaks(\n evaluateBreak(\n logicalInput.length(),\n currentX,\n targetWidth,\n potentialLineBreaks,\n 0,\n true));\n}\n\nfunction getAnchorAlignment(anchor: SymbolAnchor) {\n let horizontalAlign = 0.5, verticalAlign = 0.5;\n\n switch (anchor) {\n case 'right':\n case 'top-right':\n case 'bottom-right':\n horizontalAlign = 1;\n break;\n case 'left':\n case 'top-left':\n case 'bottom-left':\n horizontalAlign = 0;\n break;\n }\n\n switch (anchor) {\n case 'bottom':\n case 'bottom-right':\n case 'bottom-left':\n verticalAlign = 1;\n break;\n case 'top':\n case 'top-right':\n case 'top-left':\n verticalAlign = 0;\n break;\n }\n\n return {horizontalAlign, verticalAlign};\n}\n\nfunction shapeLines(shaping: Shaping,\n glyphMap: {\n [_: string]: {\n [_: number]: StyleGlyph;\n };\n },\n glyphPositions: {\n [_: string]: {\n [_: number]: GlyphPosition;\n };\n },\n imagePositions: {[_: string]: ImagePosition},\n lines: Array,\n lineHeight: number,\n textAnchor: SymbolAnchor,\n textJustify: TextJustify,\n writingMode: WritingMode.horizontal | WritingMode.vertical,\n spacing: number,\n allowVerticalPlacement: boolean,\n layoutTextSizeThisZoom: number) {\n\n let x = 0;\n let y = SHAPING_DEFAULT_OFFSET;\n\n let maxLineLength = 0;\n let maxLineHeight = 0;\n\n const justify =\n textJustify === 'right' ? 1 :\n textJustify === 'left' ? 0 : 0.5;\n\n let lineIndex = 0;\n for (const line of lines) {\n line.trim();\n\n const lineMaxScale = line.getMaxScale();\n const maxLineOffset = (lineMaxScale - 1) * ONE_EM;\n const positionedLine = {positionedGlyphs: [], lineOffset: 0};\n shaping.positionedLines[lineIndex] = positionedLine;\n const positionedGlyphs = positionedLine.positionedGlyphs;\n let lineOffset = 0.0;\n\n if (!line.length()) {\n y += lineHeight; // Still need a line feed after empty line\n ++lineIndex;\n continue;\n }\n\n for (let i = 0; i < line.length(); i++) {\n const section = line.getSection(i);\n const sectionIndex = line.getSectionIndex(i);\n const codePoint = line.getCharCode(i);\n let baselineOffset = 0.0;\n let metrics = null;\n let rect = null;\n let imageName = null;\n let verticalAdvance = ONE_EM;\n const vertical = !(writingMode === WritingMode.horizontal ||\n // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled.\n (!allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint)) ||\n // If vertical placement is enabled, don't verticalize glyphs that\n // are from complex text layout script, or whitespaces.\n (allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint))));\n\n if (!section.imageName) {\n const positions = glyphPositions[section.fontStack];\n const glyphPosition = positions && positions[codePoint];\n if (glyphPosition && glyphPosition.rect) {\n rect = glyphPosition.rect;\n metrics = glyphPosition.metrics;\n } else {\n const glyphs = glyphMap[section.fontStack];\n const glyph = glyphs && glyphs[codePoint];\n if (!glyph) continue;\n metrics = glyph.metrics;\n }\n\n // We don't know the baseline, but since we're laying out\n // at 24 points, we can calculate how much it will move when\n // we scale up or down.\n baselineOffset = (lineMaxScale - section.scale) * ONE_EM;\n } else {\n const imagePosition = imagePositions[section.imageName];\n if (!imagePosition) continue;\n imageName = section.imageName;\n shaping.iconsInText = shaping.iconsInText || true;\n rect = imagePosition.paddedRect;\n const size = imagePosition.displaySize;\n // If needed, allow to set scale factor for an image using\n // alias \"image-scale\" that could be alias for \"font-scale\"\n // when FormattedSection is an image section.\n section.scale = section.scale * ONE_EM / layoutTextSizeThisZoom;\n\n metrics = {width: size[0],\n height: size[1],\n left: IMAGE_PADDING,\n top: -GLYPH_PBF_BORDER,\n advance: vertical ? size[1] : size[0]};\n\n // Difference between one EM and an image size.\n // Aligns bottom of an image to a baseline level.\n const imageOffset = ONE_EM - size[1] * section.scale;\n baselineOffset = maxLineOffset + imageOffset;\n verticalAdvance = metrics.advance;\n\n // Difference between height of an image and one EM at max line scale.\n // Pushes current line down if an image size is over 1 EM at max line scale.\n const offset = vertical ? size[0] * section.scale - ONE_EM * lineMaxScale :\n size[1] * section.scale - ONE_EM * lineMaxScale;\n if (offset > 0 && offset > lineOffset) {\n lineOffset = offset;\n }\n }\n\n if (!vertical) {\n positionedGlyphs.push({glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect});\n x += metrics.advance * section.scale + spacing;\n } else {\n shaping.verticalizable = true;\n positionedGlyphs.push({glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect});\n x += verticalAdvance * section.scale + spacing;\n }\n }\n\n // Only justify if we placed at least one glyph\n if (positionedGlyphs.length !== 0) {\n const lineLength = x - spacing;\n maxLineLength = Math.max(lineLength, maxLineLength);\n justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify, lineOffset);\n }\n\n x = 0;\n const currentLineHeight = lineHeight * lineMaxScale + lineOffset;\n positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset);\n y += currentLineHeight;\n maxLineHeight = Math.max(currentLineHeight, maxLineHeight);\n ++lineIndex;\n }\n\n // Calculate the bounding box and justify / align text block.\n const height = y - SHAPING_DEFAULT_OFFSET;\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(textAnchor);\n align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, height, lines.length);\n\n shaping.top += -verticalAlign * height;\n shaping.bottom = shaping.top + height;\n shaping.left += -horizontalAlign * maxLineLength;\n shaping.right = shaping.left + maxLineLength;\n}\n\n// justify right = 1, left = 0, center = 0.5\nfunction justifyLine(positionedGlyphs: Array,\n start: number,\n end: number,\n justify: 1 | 0 | 0.5,\n lineOffset: number) {\n if (!justify && !lineOffset)\n return;\n\n const lastPositionedGlyph = positionedGlyphs[end];\n const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale;\n const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify;\n\n for (let j = start; j <= end; j++) {\n positionedGlyphs[j].x -= lineIndent;\n positionedGlyphs[j].y += lineOffset;\n }\n}\n\nfunction align(positionedLines: Array,\n justify: number,\n horizontalAlign: number,\n verticalAlign: number,\n maxLineLength: number,\n maxLineHeight: number,\n lineHeight: number,\n blockHeight: number,\n lineCount: number) {\n const shiftX = (justify - horizontalAlign) * maxLineLength;\n let shiftY = 0;\n\n if (maxLineHeight !== lineHeight) {\n shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET;\n } else {\n shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight;\n }\n\n for (const line of positionedLines) {\n for (const positionedGlyph of line.positionedGlyphs) {\n positionedGlyph.x += shiftX;\n positionedGlyph.y += shiftY;\n }\n }\n}\n\nexport type PositionedIcon = {\n image: ImagePosition;\n top: number;\n bottom: number;\n left: number;\n right: number;\n collisionPadding?: [number, number, number, number];\n};\n\nfunction shapeIcon(\n image: ImagePosition,\n iconOffset: [number, number],\n iconAnchor: SymbolAnchor\n): PositionedIcon {\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(iconAnchor);\n const dx = iconOffset[0];\n const dy = iconOffset[1];\n const x1 = dx - image.displaySize[0] * horizontalAlign;\n const x2 = x1 + image.displaySize[0];\n const y1 = dy - image.displaySize[1] * verticalAlign;\n const y2 = y1 + image.displaySize[1];\n return {image, top: y1, bottom: y2, left: x1, right: x2};\n}\n\nexport interface Box {\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n}\n\n/**\n * Called after a PositionedIcon has already been run through fitIconToText,\n * but needs further adjustment to apply textFitWidth and textFitHeight.\n * @param shapedIcon - The icon that will be adjusted.\n * @returns Extents of the shapedIcon with text fit adjustments if necessary.\n */\nfunction applyTextFit(shapedIcon: PositionedIcon): Box {\n // Assume shapedIcon.image is set or this wouldn't be called.\n // Size of the icon after it was adjusted using stretchX and Y\n let iconLeft = shapedIcon.left;\n let iconTop = shapedIcon.top;\n let iconWidth = shapedIcon.right - iconLeft;\n let iconHeight = shapedIcon.bottom - iconTop;\n // Size of the original content area\n const contentWidth = shapedIcon.image.content[2] - shapedIcon.image.content[0];\n const contentHeight = shapedIcon.image.content[3] - shapedIcon.image.content[1];\n const textFitWidth = shapedIcon.image.textFitWidth ?? TextFit.stretchOrShrink;\n const textFitHeight = shapedIcon.image.textFitHeight ?? TextFit.stretchOrShrink;\n const contentAspectRatio = contentWidth / contentHeight;\n // Scale to the proportional axis first note that height takes precedence if\n // both axes are set to proportional.\n if (textFitHeight === TextFit.proportional) {\n if ((textFitWidth === TextFit.stretchOnly && iconWidth / iconHeight < contentAspectRatio) || textFitWidth === TextFit.proportional) {\n // Push the width of the icon back out to match the content aspect ratio\n const newIconWidth = Math.ceil(iconHeight * contentAspectRatio);\n iconLeft *= newIconWidth / iconWidth;\n iconWidth = newIconWidth;\n }\n } else if (textFitWidth === TextFit.proportional) {\n if (textFitHeight === TextFit.stretchOnly && contentAspectRatio !== 0 && iconWidth / iconHeight > contentAspectRatio) {\n // Push the height of the icon back out to match the content aspect ratio\n const newIconHeight = Math.ceil(iconWidth / contentAspectRatio);\n iconTop *= newIconHeight / iconHeight;\n iconHeight = newIconHeight;\n }\n } else {\n // If neither textFitHeight nor textFitWidth are proportional then\n // there is no effect since the content rectangle should be precisely\n // matched to the content\n }\n return {x1: iconLeft, y1: iconTop, x2: iconLeft + iconWidth, y2: iconTop + iconHeight};\n}\n\nfunction fitIconToText(\n shapedIcon: PositionedIcon,\n shapedText: Shaping,\n textFit: string,\n padding: [number, number, number, number],\n iconOffset: [number, number],\n fontScale: number\n): PositionedIcon {\n\n const image = shapedIcon.image;\n\n let collisionPadding;\n if (image.content) {\n const content = image.content;\n const pixelRatio = image.pixelRatio || 1;\n collisionPadding = [\n content[0] / pixelRatio,\n content[1] / pixelRatio,\n image.displaySize[0] - content[2] / pixelRatio,\n image.displaySize[1] - content[3] / pixelRatio\n ];\n }\n\n // We don't respect the icon-anchor, because icon-text-fit is set. Instead,\n // the icon will be centered on the text, then stretched in the given\n // dimensions.\n\n const textLeft = shapedText.left * fontScale;\n const textRight = shapedText.right * fontScale;\n\n let top, right, bottom, left;\n if (textFit === 'width' || textFit === 'both') {\n // Stretched horizontally to the text width\n left = iconOffset[0] + textLeft - padding[3];\n right = iconOffset[0] + textRight + padding[1];\n } else {\n // Centered on the text\n left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2;\n right = left + image.displaySize[0];\n }\n\n const textTop = shapedText.top * fontScale;\n const textBottom = shapedText.bottom * fontScale;\n if (textFit === 'height' || textFit === 'both') {\n // Stretched vertically to the text height\n top = iconOffset[1] + textTop - padding[0];\n bottom = iconOffset[1] + textBottom + padding[2];\n } else {\n // Centered on the text\n top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2;\n bottom = top + image.displaySize[1];\n }\n\n return {image, top, right, bottom, left, collisionPadding};\n}\n","import {Interpolate, interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {clamp} from '../util/util';\nimport {EvaluationParameters} from '../style/evaluation_parameters';\n\nimport type {PropertyValue, PossiblyEvaluatedPropertyValue} from '../style/properties';\nimport type {InterpolationType} from '@maplibre/maplibre-gl-style-spec';\n\nconst MAX_GLYPH_ICON_SIZE = 255;\nconst SIZE_PACK_FACTOR = 128;\nconst MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR;\n\nexport {getSizeData, evaluateSizeForFeature, evaluateSizeForZoom, SIZE_PACK_FACTOR, MAX_GLYPH_ICON_SIZE, MAX_PACKED_SIZE};\n\nexport type SizeData = {\n kind: 'constant';\n layoutSize: number;\n} | {\n kind: 'source';\n} | {\n kind: 'camera';\n minZoom: number;\n maxZoom: number;\n minSize: number;\n maxSize: number;\n interpolationType: InterpolationType;\n} | {\n kind: 'composite';\n minZoom: number;\n maxZoom: number;\n interpolationType: InterpolationType;\n};\n\nexport type EvaluatedZoomSize = {uSizeT: number; uSize: number};\n\n// For {text,icon}-size, get the bucket-level data that will be needed by\n// the painter to set symbol-size-related uniforms\nfunction getSizeData(\n tileZoom: number,\n value: PropertyValue>\n): SizeData {\n const {expression} = value;\n\n if (expression.kind === 'constant') {\n const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1));\n return {kind: 'constant', layoutSize};\n\n } else if (expression.kind === 'source') {\n return {kind: 'source'};\n\n } else {\n const {zoomStops, interpolationType} = expression;\n\n // calculate covering zoom stops for zoom-dependent values\n let lower = 0;\n while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) lower++;\n lower = Math.max(0, lower - 1);\n let upper = lower;\n while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) upper++;\n upper = Math.min(zoomStops.length - 1, upper);\n\n const minZoom = zoomStops[lower];\n const maxZoom = zoomStops[upper];\n\n // We'd like to be able to use CameraExpression or CompositeExpression in these\n // return types rather than ExpressionSpecification, but the former are not\n // transferrable across Web Worker boundaries.\n if (expression.kind === 'composite') {\n return {kind: 'composite', minZoom, maxZoom, interpolationType};\n }\n\n // for camera functions, also save off the function values\n // evaluated at the covering zoom levels\n const minSize = expression.evaluate(new EvaluationParameters(minZoom));\n const maxSize = expression.evaluate(new EvaluationParameters(maxZoom));\n\n return {kind: 'camera', minZoom, maxZoom, minSize, maxSize, interpolationType};\n }\n}\n\nfunction evaluateSizeForFeature(sizeData: SizeData,\n {\n uSize,\n uSizeT\n }: {\n uSize: number;\n uSizeT: number;\n },\n {\n lowerSize,\n upperSize\n }: {\n lowerSize: number;\n upperSize: number;\n }): number {\n if (sizeData.kind === 'source') {\n return lowerSize / SIZE_PACK_FACTOR;\n } else if (sizeData.kind === 'composite') {\n return interpolates.number(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT);\n }\n return uSize;\n}\n\nfunction evaluateSizeForZoom(sizeData: SizeData, zoom: number): EvaluatedZoomSize {\n let uSizeT = 0;\n let uSize = 0;\n\n if (sizeData.kind === 'constant') {\n uSize = sizeData.layoutSize;\n\n } else if (sizeData.kind !== 'source') {\n const {interpolationType, minZoom, maxZoom} = sizeData;\n\n // Even though we could get the exact value of the camera function\n // at z = tr.zoom, we intentionally do not: instead, we interpolate\n // between the camera function values at a pair of zoom stops covering\n // [tileZoom, tileZoom + 1] in order to be consistent with this\n // restriction on composite functions\n const t = !interpolationType ? 0 : clamp(\n Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1);\n\n if (sizeData.kind === 'camera') {\n uSize = interpolates.number(sizeData.minSize, sizeData.maxSize, t);\n } else {\n uSizeT = t;\n }\n }\n\n return {uSizeT, uSize};\n}\n","import {SymbolLayoutPropsPossiblyEvaluated} from './symbol_style_layer_properties.g';\nimport type {SymbolLayoutProps} from './symbol_style_layer_properties.g';\nimport {PossiblyEvaluated} from '../properties';\n\n/**\n * The overlap mode for properties like `icon-overlap`and `text-overlap`\n */\nexport type OverlapMode = 'never' | 'always' | 'cooperative';\n\nexport function getOverlapMode(layout: PossiblyEvaluated, overlapProp: 'icon-overlap', allowOverlapProp: 'icon-allow-overlap'): OverlapMode;\nexport function getOverlapMode(layout: PossiblyEvaluated, overlapProp: 'text-overlap', allowOverlapProp: 'text-allow-overlap'): OverlapMode;\nexport function getOverlapMode(layout: PossiblyEvaluated, overlapProp: 'icon-overlap' | 'text-overlap', allowOverlapProp: 'icon-allow-overlap' | 'text-allow-overlap'): OverlapMode {\n let result: OverlapMode = 'never';\n const overlap = layout.get(overlapProp);\n\n if (overlap) {\n // if -overlap is set, use it\n result = overlap;\n } else if (layout.get(allowOverlapProp)) {\n // fall back to -allow-overlap, with false='never', true='always'\n result = 'always';\n }\n\n return result;\n}\n","import {\n symbolLayoutAttributes,\n collisionVertexAttributes,\n collisionBoxLayout,\n dynamicLayoutAttributes,\n} from './symbol_attributes';\n\nimport {SymbolLayoutArray,\n SymbolDynamicLayoutArray,\n SymbolOpacityArray,\n CollisionBoxLayoutArray,\n CollisionVertexArray,\n PlacedSymbolArray,\n SymbolInstanceArray,\n GlyphOffsetArray,\n SymbolLineVertexArray,\n TextAnchorOffsetArray\n} from '../array_types.g';\n\nimport Point from '@mapbox/point-geometry';\nimport {SegmentVector} from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {TriangleIndexArray, LineIndexArray} from '../index_array_type';\nimport {transformText} from '../../symbol/transform_text';\nimport {mergeLines} from '../../symbol/merge_lines';\nimport {allowsVerticalWritingMode, stringContainsRTLText} from '../../util/script_detection';\nimport {WritingMode} from '../../symbol/shaping';\nimport {loadGeometry} from '../load_geometry';\nimport {toEvaluationFeature} from '../evaluation_feature';\nimport mvt from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = mvt.VectorTileFeature.types;\nimport {verticalizedCharacterMap} from '../../util/verticalize_punctuation';\nimport {Anchor} from '../../symbol/anchor';\nimport {getSizeData, MAX_PACKED_SIZE} from '../../symbol/symbol_size';\n\nimport {register} from '../../util/web_worker_transfer';\nimport {EvaluationParameters} from '../../style/evaluation_parameters';\nimport {Formatted, ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\nimport {rtlWorkerPlugin} from '../../source/rtl_text_plugin_worker';\nimport {mat4} from 'gl-matrix';\nimport {getOverlapMode} from '../../style/style_layer/overlap_mode';\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\nimport type {CollisionBoxArray, CollisionBox, SymbolInstance} from '../array_types.g';\nimport type {StructArray, StructArrayMember, ViewType} from '../../util/struct_array';\nimport type {SymbolStyleLayer} from '../../style/style_layer/symbol_style_layer';\nimport type {Context} from '../../gl/context';\nimport type {IndexBuffer} from '../../gl/index_buffer';\nimport type {VertexBuffer} from '../../gl/vertex_buffer';\nimport type {SymbolQuad} from '../../symbol/quads';\nimport type {SizeData} from '../../symbol/symbol_size';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\nimport type {VectorTileLayer} from '@mapbox/vector-tile';\n\nexport type SingleCollisionBox = {\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n anchorPointX: number;\n anchorPointY: number;\n};\n\nexport type CollisionArrays = {\n textBox?: SingleCollisionBox;\n verticalTextBox?: SingleCollisionBox;\n iconBox?: SingleCollisionBox;\n verticalIconBox?: SingleCollisionBox;\n textFeatureIndex?: number;\n verticalTextFeatureIndex?: number;\n iconFeatureIndex?: number;\n verticalIconFeatureIndex?: number;\n};\n\nexport type SymbolFeature = {\n sortKey: number | void;\n text: Formatted | void;\n icon: ResolvedImage;\n index: number;\n sourceLayerIndex: number;\n geometry: Array>;\n properties: any;\n type: 'Unknown' | 'Point' | 'LineString' | 'Polygon';\n id?: any;\n};\n\nexport type SortKeyRange = {\n sortKey: number;\n symbolInstanceStart: number;\n symbolInstanceEnd: number;\n};\n\n// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them\n// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph\n// 7 bits are for the current opacity, and the lowest bit is the target opacity\n\n// actually defined in symbol_attributes.js\n// const placementOpacityAttributes = [\n// { name: 'a_fade_opacity', components: 1, type: 'Uint32' }\n// ];\nconst shaderOpacityAttributes = [\n {name: 'a_fade_opacity', components: 1, type: 'Uint8' as ViewType, offset: 0}\n];\n\nfunction addVertex(\n array: StructArray,\n anchorX: number,\n anchorY: number,\n ox: number,\n oy: number,\n tx: number,\n ty: number,\n sizeVertex: number,\n isSDF: boolean,\n pixelOffsetX: number,\n pixelOffsetY: number,\n minFontScaleX: number,\n minFontScaleY: number\n) {\n const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0;\n const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0;\n array.emplaceBack(\n // a_pos_offset\n anchorX,\n anchorY,\n Math.round(ox * 32),\n Math.round(oy * 32),\n\n // a_data\n tx, // x coordinate of symbol on glyph atlas texture\n ty, // y coordinate of symbol on glyph atlas texture\n (aSizeX << 1) + (isSDF ? 1 : 0),\n aSizeY,\n pixelOffsetX * 16,\n pixelOffsetY * 16,\n minFontScaleX * 256,\n minFontScaleY * 256\n );\n}\n\nfunction addDynamicAttributes(dynamicLayoutVertexArray: StructArray, p: Point, angle: number) {\n dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n}\n\nfunction containsRTLText(formattedText: Formatted): boolean {\n for (const section of formattedText.sections) {\n if (stringContainsRTLText(section.text)) {\n return true;\n }\n }\n return false;\n}\n\nexport class SymbolBuffers {\n layoutVertexArray: SymbolLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n programConfigurations: ProgramConfigurationSet;\n segments: SegmentVector;\n\n dynamicLayoutVertexArray: SymbolDynamicLayoutArray;\n dynamicLayoutVertexBuffer: VertexBuffer;\n\n opacityVertexArray: SymbolOpacityArray;\n opacityVertexBuffer: VertexBuffer;\n hasVisibleVertices: boolean;\n\n collisionVertexArray: CollisionVertexArray;\n collisionVertexBuffer: VertexBuffer;\n\n placedSymbolArray: PlacedSymbolArray;\n\n constructor(programConfigurations: ProgramConfigurationSet) {\n this.layoutVertexArray = new SymbolLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = programConfigurations;\n this.segments = new SegmentVector();\n this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray();\n this.opacityVertexArray = new SymbolOpacityArray();\n this.hasVisibleVertices = false;\n this.placedSymbolArray = new PlacedSymbolArray();\n }\n\n isEmpty() {\n return this.layoutVertexArray.length === 0 &&\n this.indexArray.length === 0 &&\n this.dynamicLayoutVertexArray.length === 0 &&\n this.opacityVertexArray.length === 0;\n }\n\n upload(context: Context, dynamicIndexBuffer: boolean, upload?: boolean, update?: boolean) {\n if (this.isEmpty()) {\n return;\n }\n\n if (upload) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members);\n this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer);\n this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true);\n this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true);\n // This is a performance hack so that we can write to opacityVertexArray with uint32s\n // even though the shaders read uint8s\n this.opacityVertexBuffer.itemSize = 1;\n }\n if (upload || update) {\n this.programConfigurations.upload(context);\n }\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n this.dynamicLayoutVertexBuffer.destroy();\n this.opacityVertexBuffer.destroy();\n }\n}\n\nregister('SymbolBuffers', SymbolBuffers);\n\nclass CollisionBuffers {\n layoutVertexArray: StructArray;\n layoutAttributes: Array;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray | LineIndexArray;\n indexBuffer: IndexBuffer;\n\n segments: SegmentVector;\n\n collisionVertexArray: CollisionVertexArray;\n collisionVertexBuffer: VertexBuffer;\n\n constructor(LayoutArray: {\n new (...args: any): StructArray;\n },\n layoutAttributes: Array,\n IndexArray: {\n new (...args: any): TriangleIndexArray | LineIndexArray;\n }) {\n this.layoutVertexArray = new LayoutArray();\n this.layoutAttributes = layoutAttributes;\n this.indexArray = new IndexArray();\n this.segments = new SegmentVector();\n this.collisionVertexArray = new CollisionVertexArray();\n }\n\n upload(context: Context) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true);\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.segments.destroy();\n this.collisionVertexBuffer.destroy();\n }\n}\n\nregister('CollisionBuffers', CollisionBuffers);\n\n/**\n * @internal\n * Unlike other buckets, which simply implement #addFeature with type-specific\n * logic for (essentially) triangulating feature geometries, SymbolBucket\n * requires specialized behavior:\n *\n * 1. WorkerTile#parse(), the logical owner of the bucket creation process,\n * calls SymbolBucket#populate(), which resolves text and icon tokens on\n * each feature, adds each glyphs and symbols needed to the passed-in\n * collections options.glyphDependencies and options.iconDependencies, and\n * stores the feature data for use in subsequent step (this.features).\n *\n * 2. WorkerTile asynchronously requests from the main thread all of the glyphs\n * and icons needed (by this bucket and any others). When glyphs and icons\n * have been received, the WorkerTile creates a CollisionIndex and invokes:\n *\n * 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and\n * layout on a Symbol Bucket. This step populates:\n * `this.symbolInstances`: metadata on generated symbols\n * `this.collisionBoxArray`: collision data for use by foreground\n * `this.text`: SymbolBuffers for text symbols\n * `this.icons`: SymbolBuffers for icons\n * `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes\n * `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes\n * The results are sent to the foreground for rendering\n *\n * 4. placement.ts is run on the foreground,\n * and uses the CollisionIndex along with current camera settings to determine\n * which symbols can actually show on the map. Collided symbols are hidden\n * using a dynamic \"OpacityVertexArray\".\n */\nexport class SymbolBucket implements Bucket {\n static MAX_GLYPHS: number;\n static addDynamicAttributes: typeof addDynamicAttributes;\n\n collisionBoxArray: CollisionBoxArray;\n zoom: number;\n overscaling: number;\n layers: Array;\n layerIds: Array;\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n\n index: number;\n sdfIcons: boolean;\n iconsInText: boolean;\n iconsNeedLinear: boolean;\n bucketInstanceId: number;\n justReloaded: boolean;\n hasPattern: boolean;\n\n textSizeData: SizeData;\n iconSizeData: SizeData;\n\n glyphOffsetArray: GlyphOffsetArray;\n lineVertexArray: SymbolLineVertexArray;\n features: Array;\n symbolInstances: SymbolInstanceArray;\n textAnchorOffsets: TextAnchorOffsetArray;\n collisionArrays: Array;\n sortKeyRanges: Array;\n pixelRatio: number;\n tilePixelRatio: number;\n compareText: {[_: string]: Array};\n fadeStartTime: number;\n sortFeaturesByKey: boolean;\n sortFeaturesByY: boolean;\n canOverlap: boolean;\n sortedAngle: number;\n featureSortOrder: Array;\n\n collisionCircleArray: Array;\n placementInvProjMatrix: mat4;\n placementViewportMatrix: mat4;\n\n text: SymbolBuffers;\n icon: SymbolBuffers;\n textCollisionBox: CollisionBuffers;\n iconCollisionBox: CollisionBuffers;\n uploaded: boolean;\n sourceLayerIndex: number;\n sourceID: string;\n symbolInstanceIndexes: Array;\n writingModes: WritingMode[];\n allowVerticalPlacement: boolean;\n hasRTLText: boolean;\n\n constructor(options: BucketParameters) {\n this.collisionBoxArray = options.collisionBoxArray;\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.pixelRatio = options.pixelRatio;\n this.sourceLayerIndex = options.sourceLayerIndex;\n this.hasPattern = false;\n this.hasRTLText = false;\n this.sortKeyRanges = [];\n\n this.collisionCircleArray = [];\n this.placementInvProjMatrix = mat4.identity([] as any);\n this.placementViewportMatrix = mat4.identity([] as any);\n\n const layer = this.layers[0];\n const unevaluatedLayoutValues = layer._unevaluatedLayout._values;\n\n this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']);\n this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']);\n\n const layout = this.layers[0].layout;\n const sortKey = layout.get('symbol-sort-key');\n const zOrder = layout.get('symbol-z-order');\n this.canOverlap =\n getOverlapMode(layout, 'text-overlap', 'text-allow-overlap') !== 'never' ||\n getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap') !== 'never' ||\n layout.get('text-ignore-placement') ||\n layout.get('icon-ignore-placement');\n this.sortFeaturesByKey = zOrder !== 'viewport-y' && !sortKey.isConstant();\n const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey);\n this.sortFeaturesByY = zOrderByViewportY && this.canOverlap;\n\n if (layout.get('symbol-placement') === 'point') {\n this.writingModes = layout.get('text-writing-mode').map(wm => WritingMode[wm]);\n }\n\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n\n this.sourceID = options.sourceID;\n }\n\n createArrays() {\n this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^text/.test(property)));\n this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^icon/.test(property)));\n\n this.glyphOffsetArray = new GlyphOffsetArray();\n this.lineVertexArray = new SymbolLineVertexArray();\n this.symbolInstances = new SymbolInstanceArray();\n this.textAnchorOffsets = new TextAnchorOffsetArray();\n }\n\n private calculateGlyphDependencies(\n text: string,\n stack: {[_: number]: boolean},\n textAlongLine: boolean,\n allowVerticalPlacement: boolean,\n doesAllowVerticalWritingMode: boolean) {\n\n for (let i = 0; i < text.length; i++) {\n stack[text.charCodeAt(i)] = true;\n if ((textAlongLine || allowVerticalPlacement) && doesAllowVerticalWritingMode) {\n const verticalChar = verticalizedCharacterMap[text.charAt(i)];\n if (verticalChar) {\n stack[verticalChar.charCodeAt(0)] = true;\n }\n }\n }\n }\n\n populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID) {\n const layer = this.layers[0];\n const layout = layer.layout;\n\n const textFont = layout.get('text-font');\n const textField = layout.get('text-field');\n const iconImage = layout.get('icon-image');\n const hasText =\n (textField.value.kind !== 'constant' ||\n (textField.value.value instanceof Formatted && !textField.value.value.isEmpty()) ||\n textField.value.value.toString().length > 0) &&\n (textFont.value.kind !== 'constant' || textFont.value.value.length > 0);\n // we should always resolve the icon-image value if the property was defined in the style\n // this allows us to fire the styleimagemissing event if image evaluation returns null\n // the only way to distinguish between null returned from a coalesce statement with no valid images\n // and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object\n const hasIcon = iconImage.value.kind !== 'constant' || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0;\n const symbolSortKey = layout.get('symbol-sort-key');\n\n this.features = [];\n\n if (!hasText && !hasIcon) {\n return;\n }\n\n const icons = options.iconDependencies;\n const stacks = options.glyphDependencies;\n const availableImages = options.availableImages;\n const globalProperties = new EvaluationParameters(this.zoom);\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n\n const needGeometry = layer._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) {\n continue;\n }\n\n if (!needGeometry) evaluationFeature.geometry = loadGeometry(feature);\n\n let text: Formatted | void;\n if (hasText) {\n // Expression evaluation will automatically coerce to Formatted\n // but plain string token evaluation skips that pathway so do the\n // conversion here.\n const resolvedTokens = layer.getValueAndResolveTokens('text-field', evaluationFeature, canonical, availableImages);\n const formattedText = Formatted.factory(resolvedTokens);\n\n // on this instance: if hasRTLText is already true, all future calls to containsRTLText can be skipped.\n const bucketHasRTLText = this.hasRTLText = (this.hasRTLText || containsRTLText(formattedText));\n if (\n !bucketHasRTLText || // non-rtl text so can proceed safely\n rtlWorkerPlugin.getRTLTextPluginStatus() === 'unavailable' || // We don't intend to lazy-load the rtl text plugin, so proceed with incorrect shaping\n bucketHasRTLText && rtlWorkerPlugin.isParsed() // Use the rtlText plugin to shape text\n ) {\n text = transformText(formattedText, layer, evaluationFeature);\n }\n }\n\n let icon: ResolvedImage;\n if (hasIcon) {\n // Expression evaluation will automatically coerce to Image\n // but plain string token evaluation skips that pathway so do the\n // conversion here.\n const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages);\n if (resolvedTokens instanceof ResolvedImage) {\n icon = resolvedTokens;\n } else {\n icon = ResolvedImage.fromString(resolvedTokens);\n }\n }\n\n if (!text && !icon) {\n continue;\n }\n const sortKey = this.sortFeaturesByKey ?\n symbolSortKey.evaluate(evaluationFeature, {}, canonical) :\n undefined;\n\n const symbolFeature: SymbolFeature = {\n id,\n text,\n icon,\n index,\n sourceLayerIndex,\n geometry: evaluationFeature.geometry,\n properties: feature.properties,\n type: vectorTileFeatureTypes[feature.type],\n sortKey\n };\n this.features.push(symbolFeature);\n\n if (icon) {\n icons[icon.name] = true;\n }\n\n if (text) {\n const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(',');\n const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point';\n this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(WritingMode.vertical) >= 0;\n for (const section of text.sections) {\n if (!section.image) {\n const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString());\n const sectionFont = section.fontStack || fontStack;\n const sectionStack = stacks[sectionFont] = stacks[sectionFont] || {};\n this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode);\n } else {\n // Add section image to the list of dependencies.\n icons[section.image.name] = true;\n }\n }\n }\n }\n\n if (layout.get('symbol-placement') === 'line') {\n // Merge adjacent lines with the same text to improve labelling.\n // It's better to place labels on one long line than on many short segments.\n this.features = mergeLines(this.features);\n }\n\n if (this.sortFeaturesByKey) {\n this.features.sort((a, b) => {\n // a.sortKey is always a number when sortFeaturesByKey is true\n return (a.sortKey as number) - (b.sortKey as number);\n });\n }\n }\n\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {\n if (!this.stateDependentLayers.length) return;\n this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions);\n this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions);\n }\n\n isEmpty() {\n // When the bucket encounters only rtl-text but the plugin isn't loaded, no symbol instances will be created.\n // In order for the bucket to be serialized, and not discarded as an empty bucket both checks are necessary.\n return this.symbolInstances.length === 0 && !this.hasRTLText;\n }\n\n uploadPending() {\n return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload;\n }\n\n upload(context: Context) {\n if (!this.uploaded && this.hasDebugData()) {\n this.textCollisionBox.upload(context);\n this.iconCollisionBox.upload(context);\n }\n this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload);\n this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload);\n this.uploaded = true;\n }\n\n destroyDebugData() {\n this.textCollisionBox.destroy();\n this.iconCollisionBox.destroy();\n }\n\n destroy() {\n this.text.destroy();\n this.icon.destroy();\n\n if (this.hasDebugData()) {\n this.destroyDebugData();\n }\n }\n\n addToLineVertexArray(anchor: Anchor, line: any) {\n const lineStartIndex = this.lineVertexArray.length;\n if (anchor.segment !== undefined) {\n let sumForwardLength = anchor.dist(line[anchor.segment + 1]);\n let sumBackwardLength = anchor.dist(line[anchor.segment]);\n const vertices = {};\n for (let i = anchor.segment + 1; i < line.length; i++) {\n vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength};\n if (i < line.length - 1) {\n sumForwardLength += line[i + 1].dist(line[i]);\n }\n }\n for (let i = anchor.segment || 0; i >= 0; i--) {\n vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumBackwardLength};\n if (i > 0) {\n sumBackwardLength += line[i - 1].dist(line[i]);\n }\n }\n for (let i = 0; i < line.length; i++) {\n const vertex = vertices[i];\n this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor);\n }\n }\n return {\n lineStartIndex,\n lineLength: this.lineVertexArray.length - lineStartIndex\n };\n }\n\n addSymbols(arrays: SymbolBuffers,\n quads: Array,\n sizeVertex: any,\n lineOffset: [number, number],\n alongLine: boolean,\n feature: SymbolFeature,\n writingMode: WritingMode,\n labelAnchor: Anchor,\n lineStartIndex: number,\n lineLength: number,\n associatedIconIndex: number,\n canonical: CanonicalTileID) {\n const indexArray = arrays.indexArray;\n const layoutVertexArray = arrays.layoutVertexArray;\n\n const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey as number : undefined);\n const glyphOffsetArrayStart = this.glyphOffsetArray.length;\n const vertexStartIndex = segment.vertexLength;\n\n const angle = (this.allowVerticalPlacement && writingMode === WritingMode.vertical) ? Math.PI / 2 : 0;\n\n const sections = feature.text && feature.text.sections;\n\n for (let i = 0; i < quads.length; i++) {\n const {tl, tr, bl, br, tex, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex} = quads[i];\n const index = segment.vertexLength;\n\n const y = glyphOffset[1];\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);\n\n addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle);\n\n indexArray.emplaceBack(index, index + 1, index + 2);\n indexArray.emplaceBack(index + 1, index + 2, index + 3);\n\n segment.vertexLength += 4;\n segment.primitiveLength += 2;\n\n this.glyphOffsetArray.emplaceBack(glyphOffset[0]);\n\n if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) {\n arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {}, canonical, sections && sections[sectionIndex]);\n }\n }\n\n arrays.placedSymbolArray.emplaceBack(\n labelAnchor.x, labelAnchor.y,\n glyphOffsetArrayStart,\n this.glyphOffsetArray.length - glyphOffsetArrayStart,\n vertexStartIndex,\n lineStartIndex,\n lineLength,\n labelAnchor.segment,\n sizeVertex ? sizeVertex[0] : 0,\n sizeVertex ? sizeVertex[1] : 0,\n lineOffset[0], lineOffset[1],\n writingMode,\n // placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed\n 0,\n false as unknown as number,\n // The crossTileID is only filled/used on the foreground for dynamic text anchors\n 0,\n associatedIconIndex\n );\n }\n\n _addCollisionDebugVertex(layoutVertexArray: StructArray, collisionVertexArray: StructArray, point: Point, anchorX: number, anchorY: number, extrude: Point) {\n collisionVertexArray.emplaceBack(0, 0);\n return layoutVertexArray.emplaceBack(\n // pos\n point.x,\n point.y,\n // a_anchor_pos\n anchorX,\n anchorY,\n // extrude\n Math.round(extrude.x),\n Math.round(extrude.y));\n }\n\n addCollisionDebugVertices(x1: number, y1: number, x2: number, y2: number, arrays: CollisionBuffers, boxAnchorPoint: Point, symbolInstance: SymbolInstance) {\n const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray);\n const index = segment.vertexLength;\n\n const layoutVertexArray = arrays.layoutVertexArray;\n const collisionVertexArray = arrays.collisionVertexArray;\n\n const anchorX = symbolInstance.anchorX;\n const anchorY = symbolInstance.anchorY;\n\n this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y1));\n this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y1));\n this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y2));\n this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y2));\n\n segment.vertexLength += 4;\n\n const indexArray = arrays.indexArray as LineIndexArray;\n indexArray.emplaceBack(index, index + 1);\n indexArray.emplaceBack(index + 1, index + 2);\n indexArray.emplaceBack(index + 2, index + 3);\n indexArray.emplaceBack(index + 3, index);\n\n segment.primitiveLength += 4;\n }\n\n addDebugCollisionBoxes(startIndex: number, endIndex: number, symbolInstance: SymbolInstance, isText: boolean) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = this.collisionBoxArray.get(b);\n const x1 = box.x1;\n const y1 = box.y1;\n const x2 = box.x2;\n const y2 = box.y2;\n\n this.addCollisionDebugVertices(x1, y1, x2, y2,\n isText ? this.textCollisionBox : this.iconCollisionBox,\n box.anchorPoint, symbolInstance);\n }\n }\n\n generateCollisionDebugBuffers() {\n if (this.hasDebugData()) {\n this.destroyDebugData();\n }\n\n this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);\n this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);\n\n for (let i = 0; i < this.symbolInstances.length; i++) {\n const symbolInstance = this.symbolInstances.get(i);\n this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true);\n this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true);\n this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false);\n this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false);\n }\n }\n\n // These flat arrays are meant to be quicker to iterate over than the source\n // CollisionBoxArray\n _deserializeCollisionBoxesForSymbol(\n collisionBoxArray: CollisionBoxArray,\n textStartIndex: number,\n textEndIndex: number,\n verticalTextStartIndex: number,\n verticalTextEndIndex: number,\n iconStartIndex: number,\n iconEndIndex: number,\n verticalIconStartIndex: number,\n verticalIconEndIndex: number\n ): CollisionArrays {\n\n const collisionArrays = {} as CollisionArrays;\n for (let k = textStartIndex; k < textEndIndex; k++) {\n const box: CollisionBox = collisionBoxArray.get(k);\n collisionArrays.textBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n collisionArrays.textFeatureIndex = box.featureIndex;\n break; // Only one box allowed per instance\n }\n for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) {\n const box: CollisionBox = collisionBoxArray.get(k);\n collisionArrays.verticalTextBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n collisionArrays.verticalTextFeatureIndex = box.featureIndex;\n break; // Only one box allowed per instance\n }\n for (let k = iconStartIndex; k < iconEndIndex; k++) {\n // An icon can only have one box now, so this indexing is a bit vestigial...\n const box: CollisionBox = collisionBoxArray.get(k);\n collisionArrays.iconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n collisionArrays.iconFeatureIndex = box.featureIndex;\n break; // Only one box allowed per instance\n }\n for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) {\n // An icon can only have one box now, so this indexing is a bit vestigial...\n const box: CollisionBox = collisionBoxArray.get(k);\n collisionArrays.verticalIconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n collisionArrays.verticalIconFeatureIndex = box.featureIndex;\n break; // Only one box allowed per instance\n }\n return collisionArrays;\n }\n\n deserializeCollisionBoxes(collisionBoxArray: CollisionBoxArray) {\n this.collisionArrays = [];\n for (let i = 0; i < this.symbolInstances.length; i++) {\n const symbolInstance = this.symbolInstances.get(i);\n this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(\n collisionBoxArray,\n symbolInstance.textBoxStartIndex,\n symbolInstance.textBoxEndIndex,\n symbolInstance.verticalTextBoxStartIndex,\n symbolInstance.verticalTextBoxEndIndex,\n symbolInstance.iconBoxStartIndex,\n symbolInstance.iconBoxEndIndex,\n symbolInstance.verticalIconBoxStartIndex,\n symbolInstance.verticalIconBoxEndIndex\n ));\n }\n }\n\n hasTextData() {\n return this.text.segments.get().length > 0;\n }\n\n hasIconData() {\n return this.icon.segments.get().length > 0;\n }\n\n hasDebugData() {\n return this.textCollisionBox && this.iconCollisionBox;\n }\n\n hasTextCollisionBoxData() {\n return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0;\n }\n\n hasIconCollisionBoxData() {\n return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0;\n }\n\n addIndicesForPlacedSymbol(iconOrText: SymbolBuffers, placedSymbolIndex: number) {\n const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex);\n\n const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4;\n for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) {\n iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2);\n iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3);\n }\n }\n\n getSortedSymbolIndexes(angle: number) {\n if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) {\n return this.symbolInstanceIndexes;\n }\n const sin = Math.sin(angle);\n const cos = Math.cos(angle);\n const rotatedYs = [];\n const featureIndexes = [];\n const result = [];\n\n for (let i = 0; i < this.symbolInstances.length; ++i) {\n result.push(i);\n const symbolInstance = this.symbolInstances.get(i);\n rotatedYs.push(Math.round(sin * symbolInstance.anchorX + cos * symbolInstance.anchorY) | 0);\n featureIndexes.push(symbolInstance.featureIndex);\n }\n\n result.sort((aIndex, bIndex) => {\n return (rotatedYs[aIndex] - rotatedYs[bIndex]) ||\n (featureIndexes[bIndex] - featureIndexes[aIndex]);\n });\n\n return result;\n }\n\n addToSortKeyRanges(symbolInstanceIndex: number, sortKey: number) {\n const last = this.sortKeyRanges[this.sortKeyRanges.length - 1];\n if (last && last.sortKey === sortKey) {\n last.symbolInstanceEnd = symbolInstanceIndex + 1;\n } else {\n this.sortKeyRanges.push({\n sortKey,\n symbolInstanceStart: symbolInstanceIndex,\n symbolInstanceEnd: symbolInstanceIndex + 1\n });\n }\n }\n\n sortFeatures(angle: number) {\n if (!this.sortFeaturesByY) return;\n if (this.sortedAngle === angle) return;\n\n // The current approach to sorting doesn't sort across segments so don't try.\n // Sorting within segments separately seemed not to be worth the complexity.\n if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) return;\n\n // If the symbols are allowed to overlap sort them by their vertical screen position.\n // The index array buffer is rewritten to reference the (unchanged) vertices in the\n // sorted order.\n\n // To avoid sorting the actual symbolInstance array we sort an array of indexes.\n this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle);\n this.sortedAngle = angle;\n\n this.text.indexArray.clear();\n this.icon.indexArray.clear();\n\n this.featureSortOrder = [];\n\n for (const i of this.symbolInstanceIndexes) {\n const symbolInstance = this.symbolInstances.get(i);\n this.featureSortOrder.push(symbolInstance.featureIndex);\n\n [\n symbolInstance.rightJustifiedTextSymbolIndex,\n symbolInstance.centerJustifiedTextSymbolIndex,\n symbolInstance.leftJustifiedTextSymbolIndex\n ].forEach((index, i, array) => {\n // Only add a given index the first time it shows up,\n // to avoid duplicate opacity entries when multiple justifications\n // share the same glyphs.\n if (index >= 0 && array.indexOf(index) === i) {\n this.addIndicesForPlacedSymbol(this.text, index);\n }\n });\n\n if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {\n this.addIndicesForPlacedSymbol(this.text, symbolInstance.verticalPlacedTextSymbolIndex);\n }\n\n if (symbolInstance.placedIconSymbolIndex >= 0) {\n this.addIndicesForPlacedSymbol(this.icon, symbolInstance.placedIconSymbolIndex);\n }\n\n if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) {\n this.addIndicesForPlacedSymbol(this.icon, symbolInstance.verticalPlacedIconSymbolIndex);\n }\n }\n\n if (this.text.indexBuffer) this.text.indexBuffer.updateData(this.text.indexArray);\n if (this.icon.indexBuffer) this.icon.indexBuffer.updateData(this.icon.indexArray);\n }\n}\n\nregister('SymbolBucket', SymbolBucket, {\n omit: ['layers', 'collisionBoxArray', 'features', 'compareText']\n});\n\n// this constant is based on the size of StructArray indexes used in a symbol\n// bucket--namely, glyphOffsetArrayStart\n// eg the max valid UInt16 is 65,535\n// See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation\n// lineStartIndex and textBoxStartIndex could potentially be concerns\n// but we expect there to be many fewer boxes/lines than glyphs\nSymbolBucket.MAX_GLYPHS = 65535;\n\nSymbolBucket.addDynamicAttributes = addDynamicAttributes;\n\nexport {addDynamicAttributes};\n","import type {SymbolFeature} from '../data/bucket/symbol_bucket';\n\nexport function mergeLines(features: Array): Array {\n const leftIndex: {[_: string]: number} = {};\n const rightIndex: {[_: string]: number} = {};\n const mergedFeatures = [];\n let mergedIndex = 0;\n\n function add(k) {\n mergedFeatures.push(features[k]);\n mergedIndex++;\n }\n\n function mergeFromRight(leftKey: string, rightKey: string, geom) {\n const i = rightIndex[leftKey];\n delete rightIndex[leftKey];\n rightIndex[rightKey] = i;\n\n mergedFeatures[i].geometry[0].pop();\n mergedFeatures[i].geometry[0] = mergedFeatures[i].geometry[0].concat(geom[0]);\n return i;\n }\n\n function mergeFromLeft(leftKey: string, rightKey: string, geom) {\n const i = leftIndex[rightKey];\n delete leftIndex[rightKey];\n leftIndex[leftKey] = i;\n\n mergedFeatures[i].geometry[0].shift();\n mergedFeatures[i].geometry[0] = geom[0].concat(mergedFeatures[i].geometry[0]);\n return i;\n }\n\n function getKey(text, geom, onRight?) {\n const point = onRight ? geom[0][geom[0].length - 1] : geom[0][0];\n return `${text}:${point.x}:${point.y}`;\n }\n\n for (let k = 0; k < features.length; k++) {\n const feature = features[k];\n const geom = feature.geometry;\n const text = feature.text ? feature.text.toString() : null;\n\n if (!text) {\n add(k);\n continue;\n }\n\n const leftKey = getKey(text, geom),\n rightKey = getKey(text, geom, true);\n\n if ((leftKey in rightIndex) && (rightKey in leftIndex) && (rightIndex[leftKey] !== leftIndex[rightKey])) {\n // found lines with the same text adjacent to both ends of the current line, merge all three\n const j = mergeFromLeft(leftKey, rightKey, geom);\n const i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry);\n\n delete leftIndex[leftKey];\n delete rightIndex[rightKey];\n\n rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i;\n mergedFeatures[j].geometry = null;\n\n } else if (leftKey in rightIndex) {\n // found mergeable line adjacent to the start of the current line, merge\n mergeFromRight(leftKey, rightKey, geom);\n\n } else if (rightKey in leftIndex) {\n // found mergeable line adjacent to the end of the current line, merge\n mergeFromLeft(leftKey, rightKey, geom);\n\n } else {\n // no adjacent lines, add as a new item\n add(k);\n leftIndex[leftKey] = mergedIndex - 1;\n rightIndex[rightKey] = mergedIndex - 1;\n }\n }\n\n return mergedFeatures.filter((f) => f.geometry);\n}\n","// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty,\n PossiblyEvaluatedPropertyValue,\n CrossFaded\n} from '../properties';\n\nimport type {Color, Formatted, Padding, ResolvedImage, VariableAnchorOffsetCollection} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n ColorType\n } from '@maplibre/maplibre-gl-style-spec';\n \nexport type SymbolLayoutProps = {\n \"symbol-placement\": DataConstantProperty<\"point\" | \"line\" | \"line-center\">,\n \"symbol-spacing\": DataConstantProperty,\n \"symbol-avoid-edges\": DataConstantProperty,\n \"symbol-sort-key\": DataDrivenProperty,\n \"symbol-z-order\": DataConstantProperty<\"auto\" | \"viewport-y\" | \"source\">,\n \"icon-allow-overlap\": DataConstantProperty,\n \"icon-overlap\": DataConstantProperty<\"never\" | \"always\" | \"cooperative\">,\n \"icon-ignore-placement\": DataConstantProperty,\n \"icon-optional\": DataConstantProperty,\n \"icon-rotation-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"icon-size\": DataDrivenProperty,\n \"icon-text-fit\": DataConstantProperty<\"none\" | \"width\" | \"height\" | \"both\">,\n \"icon-text-fit-padding\": DataConstantProperty<[number, number, number, number]>,\n \"icon-image\": DataDrivenProperty,\n \"icon-rotate\": DataDrivenProperty,\n \"icon-padding\": DataDrivenProperty,\n \"icon-keep-upright\": DataConstantProperty,\n \"icon-offset\": DataDrivenProperty<[number, number]>,\n \"icon-anchor\": DataDrivenProperty<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"icon-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"text-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"text-rotation-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"viewport-glyph\" | \"auto\">,\n \"text-field\": DataDrivenProperty,\n \"text-font\": DataDrivenProperty>,\n \"text-size\": DataDrivenProperty,\n \"text-max-width\": DataDrivenProperty,\n \"text-line-height\": DataConstantProperty,\n \"text-letter-spacing\": DataDrivenProperty,\n \"text-justify\": DataDrivenProperty<\"auto\" | \"left\" | \"center\" | \"right\">,\n \"text-radial-offset\": DataDrivenProperty,\n \"text-variable-anchor\": DataConstantProperty>,\n \"text-variable-anchor-offset\": DataDrivenProperty,\n \"text-anchor\": DataDrivenProperty<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"text-max-angle\": DataConstantProperty,\n \"text-writing-mode\": DataConstantProperty>,\n \"text-rotate\": DataDrivenProperty,\n \"text-padding\": DataConstantProperty,\n \"text-keep-upright\": DataConstantProperty,\n \"text-transform\": DataDrivenProperty<\"none\" | \"uppercase\" | \"lowercase\">,\n \"text-offset\": DataDrivenProperty<[number, number]>,\n \"text-allow-overlap\": DataConstantProperty,\n \"text-overlap\": DataConstantProperty<\"never\" | \"always\" | \"cooperative\">,\n \"text-ignore-placement\": DataConstantProperty,\n \"text-optional\": DataConstantProperty,\n};\n\nexport type SymbolLayoutPropsPossiblyEvaluated = {\n \"symbol-placement\": \"point\" | \"line\" | \"line-center\",\n \"symbol-spacing\": number,\n \"symbol-avoid-edges\": boolean,\n \"symbol-sort-key\": PossiblyEvaluatedPropertyValue,\n \"symbol-z-order\": \"auto\" | \"viewport-y\" | \"source\",\n \"icon-allow-overlap\": boolean,\n \"icon-overlap\": \"never\" | \"always\" | \"cooperative\",\n \"icon-ignore-placement\": boolean,\n \"icon-optional\": boolean,\n \"icon-rotation-alignment\": \"map\" | \"viewport\" | \"auto\",\n \"icon-size\": PossiblyEvaluatedPropertyValue,\n \"icon-text-fit\": \"none\" | \"width\" | \"height\" | \"both\",\n \"icon-text-fit-padding\": [number, number, number, number],\n \"icon-image\": PossiblyEvaluatedPropertyValue,\n \"icon-rotate\": PossiblyEvaluatedPropertyValue,\n \"icon-padding\": PossiblyEvaluatedPropertyValue,\n \"icon-keep-upright\": boolean,\n \"icon-offset\": PossiblyEvaluatedPropertyValue<[number, number]>,\n \"icon-anchor\": PossiblyEvaluatedPropertyValue<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"icon-pitch-alignment\": \"map\" | \"viewport\" | \"auto\",\n \"text-pitch-alignment\": \"map\" | \"viewport\" | \"auto\",\n \"text-rotation-alignment\": \"map\" | \"viewport\" | \"viewport-glyph\" | \"auto\",\n \"text-field\": PossiblyEvaluatedPropertyValue,\n \"text-font\": PossiblyEvaluatedPropertyValue>,\n \"text-size\": PossiblyEvaluatedPropertyValue,\n \"text-max-width\": PossiblyEvaluatedPropertyValue,\n \"text-line-height\": number,\n \"text-letter-spacing\": PossiblyEvaluatedPropertyValue,\n \"text-justify\": PossiblyEvaluatedPropertyValue<\"auto\" | \"left\" | \"center\" | \"right\">,\n \"text-radial-offset\": PossiblyEvaluatedPropertyValue,\n \"text-variable-anchor\": Array<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"text-variable-anchor-offset\": PossiblyEvaluatedPropertyValue,\n \"text-anchor\": PossiblyEvaluatedPropertyValue<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"text-max-angle\": number,\n \"text-writing-mode\": Array<\"horizontal\" | \"vertical\">,\n \"text-rotate\": PossiblyEvaluatedPropertyValue,\n \"text-padding\": number,\n \"text-keep-upright\": boolean,\n \"text-transform\": PossiblyEvaluatedPropertyValue<\"none\" | \"uppercase\" | \"lowercase\">,\n \"text-offset\": PossiblyEvaluatedPropertyValue<[number, number]>,\n \"text-allow-overlap\": boolean,\n \"text-overlap\": \"never\" | \"always\" | \"cooperative\",\n \"text-ignore-placement\": boolean,\n \"text-optional\": boolean,\n};\n\nlet layout: Properties;\nconst getLayout = () => layout = layout || new Properties({\n \"symbol-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-placement\"] as any as StylePropertySpecification),\n \"symbol-spacing\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-spacing\"] as any as StylePropertySpecification),\n \"symbol-avoid-edges\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-avoid-edges\"] as any as StylePropertySpecification),\n \"symbol-sort-key\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"symbol-sort-key\"] as any as StylePropertySpecification),\n \"symbol-z-order\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-z-order\"] as any as StylePropertySpecification),\n \"icon-allow-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-allow-overlap\"] as any as StylePropertySpecification),\n \"icon-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-overlap\"] as any as StylePropertySpecification),\n \"icon-ignore-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-ignore-placement\"] as any as StylePropertySpecification),\n \"icon-optional\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-optional\"] as any as StylePropertySpecification),\n \"icon-rotation-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-rotation-alignment\"] as any as StylePropertySpecification),\n \"icon-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-size\"] as any as StylePropertySpecification),\n \"icon-text-fit\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit\"] as any as StylePropertySpecification),\n \"icon-text-fit-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit-padding\"] as any as StylePropertySpecification),\n \"icon-image\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-image\"] as any as StylePropertySpecification),\n \"icon-rotate\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-rotate\"] as any as StylePropertySpecification),\n \"icon-padding\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-padding\"] as any as StylePropertySpecification),\n \"icon-keep-upright\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-keep-upright\"] as any as StylePropertySpecification),\n \"icon-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-offset\"] as any as StylePropertySpecification),\n \"icon-anchor\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-anchor\"] as any as StylePropertySpecification),\n \"icon-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-pitch-alignment\"] as any as StylePropertySpecification),\n \"text-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-pitch-alignment\"] as any as StylePropertySpecification),\n \"text-rotation-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-rotation-alignment\"] as any as StylePropertySpecification),\n \"text-field\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-field\"] as any as StylePropertySpecification),\n \"text-font\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-font\"] as any as StylePropertySpecification),\n \"text-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-size\"] as any as StylePropertySpecification),\n \"text-max-width\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-max-width\"] as any as StylePropertySpecification),\n \"text-line-height\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-line-height\"] as any as StylePropertySpecification),\n \"text-letter-spacing\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-letter-spacing\"] as any as StylePropertySpecification),\n \"text-justify\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-justify\"] as any as StylePropertySpecification),\n \"text-radial-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-radial-offset\"] as any as StylePropertySpecification),\n \"text-variable-anchor\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-variable-anchor\"] as any as StylePropertySpecification),\n \"text-variable-anchor-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-variable-anchor-offset\"] as any as StylePropertySpecification),\n \"text-anchor\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-anchor\"] as any as StylePropertySpecification),\n \"text-max-angle\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-max-angle\"] as any as StylePropertySpecification),\n \"text-writing-mode\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-writing-mode\"] as any as StylePropertySpecification),\n \"text-rotate\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-rotate\"] as any as StylePropertySpecification),\n \"text-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-padding\"] as any as StylePropertySpecification),\n \"text-keep-upright\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-keep-upright\"] as any as StylePropertySpecification),\n \"text-transform\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-transform\"] as any as StylePropertySpecification),\n \"text-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-offset\"] as any as StylePropertySpecification),\n \"text-allow-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-allow-overlap\"] as any as StylePropertySpecification),\n \"text-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-overlap\"] as any as StylePropertySpecification),\n \"text-ignore-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-ignore-placement\"] as any as StylePropertySpecification),\n \"text-optional\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-optional\"] as any as StylePropertySpecification),\n});\n\nexport type SymbolPaintProps = {\n \"icon-opacity\": DataDrivenProperty,\n \"icon-color\": DataDrivenProperty,\n \"icon-halo-color\": DataDrivenProperty,\n \"icon-halo-width\": DataDrivenProperty,\n \"icon-halo-blur\": DataDrivenProperty,\n \"icon-translate\": DataConstantProperty<[number, number]>,\n \"icon-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"text-opacity\": DataDrivenProperty,\n \"text-color\": DataDrivenProperty,\n \"text-halo-color\": DataDrivenProperty,\n \"text-halo-width\": DataDrivenProperty,\n \"text-halo-blur\": DataDrivenProperty,\n \"text-translate\": DataConstantProperty<[number, number]>,\n \"text-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n};\n\nexport type SymbolPaintPropsPossiblyEvaluated = {\n \"icon-opacity\": PossiblyEvaluatedPropertyValue,\n \"icon-color\": PossiblyEvaluatedPropertyValue,\n \"icon-halo-color\": PossiblyEvaluatedPropertyValue,\n \"icon-halo-width\": PossiblyEvaluatedPropertyValue,\n \"icon-halo-blur\": PossiblyEvaluatedPropertyValue,\n \"icon-translate\": [number, number],\n \"icon-translate-anchor\": \"map\" | \"viewport\",\n \"text-opacity\": PossiblyEvaluatedPropertyValue,\n \"text-color\": PossiblyEvaluatedPropertyValue,\n \"text-halo-color\": PossiblyEvaluatedPropertyValue,\n \"text-halo-width\": PossiblyEvaluatedPropertyValue,\n \"text-halo-blur\": PossiblyEvaluatedPropertyValue,\n \"text-translate\": [number, number],\n \"text-translate-anchor\": \"map\" | \"viewport\",\n};\n\nlet paint: Properties;\nconst getPaint = () => paint = paint || new Properties({\n \"icon-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-opacity\"] as any as StylePropertySpecification),\n \"icon-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-color\"] as any as StylePropertySpecification),\n \"icon-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-color\"] as any as StylePropertySpecification),\n \"icon-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-width\"] as any as StylePropertySpecification),\n \"icon-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-blur\"] as any as StylePropertySpecification),\n \"icon-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate\"] as any as StylePropertySpecification),\n \"icon-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate-anchor\"] as any as StylePropertySpecification),\n \"text-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-opacity\"] as any as StylePropertySpecification),\n \"text-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-color\"] as any as StylePropertySpecification, { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }),\n \"text-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-color\"] as any as StylePropertySpecification),\n \"text-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-width\"] as any as StylePropertySpecification),\n \"text-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-blur\"] as any as StylePropertySpecification),\n \"text-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate\"] as any as StylePropertySpecification),\n \"text-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate-anchor\"] as any as StylePropertySpecification),\n});\n\nexport default ({ get paint() { return getPaint() }, get layout() { return getLayout() } });","import type {Expression, EvaluationContext, Type, ZoomConstantExpression} from '@maplibre/maplibre-gl-style-spec';\nimport {NullType} from '@maplibre/maplibre-gl-style-spec';\nimport {PossiblyEvaluatedPropertyValue} from './properties';\nimport {register} from '../util/web_worker_transfer';\n\n// This is an internal expression class. It is only used in GL JS and\n// has GL JS dependencies which can break the standalone style-spec module\nexport class FormatSectionOverride implements Expression {\n type: Type;\n defaultValue: PossiblyEvaluatedPropertyValue;\n\n constructor(defaultValue: PossiblyEvaluatedPropertyValue) {\n if (defaultValue.property.overrides === undefined) throw new Error('overrides must be provided to instantiate FormatSectionOverride class');\n this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType;\n this.defaultValue = defaultValue;\n }\n\n evaluate(ctx: EvaluationContext) {\n if (ctx.formattedSection) {\n const overrides = this.defaultValue.property.overrides;\n if (overrides && overrides.hasOverride(ctx.formattedSection)) {\n return overrides.getOverride(ctx.formattedSection);\n }\n }\n\n if (ctx.feature && ctx.featureState) {\n return this.defaultValue.evaluate(ctx.feature, ctx.featureState);\n }\n\n return this.defaultValue.property.specification.default;\n }\n\n eachChild(fn: (_: Expression) => void) {\n if (!this.defaultValue.isConstant()) {\n const expr: ZoomConstantExpression<'source'> = (this.defaultValue.value as any);\n fn(expr._styleExpression.expression);\n }\n }\n\n // Cannot be statically evaluated, as the output depends on the evaluation context.\n outputDefined() {\n return false;\n }\n\n serialize() {\n return null;\n }\n}\n\nregister('FormatSectionOverride', FormatSectionOverride, {omit: ['defaultValue']});\n","import {StyleLayer} from '../style_layer';\n\nimport {SymbolBucket, SymbolFeature} from '../../data/bucket/symbol_bucket';\nimport {resolveTokens} from '../../util/resolve_tokens';\nimport properties, {SymbolLayoutPropsPossiblyEvaluated, SymbolPaintPropsPossiblyEvaluated} from './symbol_style_layer_properties.g';\n\nimport {\n Transitionable,\n Transitioning,\n Layout,\n PossiblyEvaluated,\n PossiblyEvaluatedPropertyValue,\n PropertyValue\n} from '../properties';\n\nimport {\n isExpression,\n StyleExpression,\n ZoomConstantExpression,\n ZoomDependentExpression,\n FormattedType,\n typeOf,\n Formatted,\n FormatExpression,\n Literal} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {BucketParameters} from '../../data/bucket';\nimport type {SymbolLayoutProps, SymbolPaintProps} from './symbol_style_layer_properties.g';\nimport type {EvaluationParameters} from '../evaluation_parameters';\nimport type {Expression, Feature, SourceExpression, LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport {FormatSectionOverride} from '../format_section_override';\n\nexport class SymbolStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout;\n layout: PossiblyEvaluated;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array) {\n super.recalculate(parameters, availableImages);\n\n if (this.layout.get('icon-rotation-alignment') === 'auto') {\n if (this.layout.get('symbol-placement') !== 'point') {\n this.layout._values['icon-rotation-alignment'] = 'map';\n } else {\n this.layout._values['icon-rotation-alignment'] = 'viewport';\n }\n }\n\n if (this.layout.get('text-rotation-alignment') === 'auto') {\n if (this.layout.get('symbol-placement') !== 'point') {\n this.layout._values['text-rotation-alignment'] = 'map';\n } else {\n this.layout._values['text-rotation-alignment'] = 'viewport';\n }\n }\n\n // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment`\n if (this.layout.get('text-pitch-alignment') === 'auto') {\n this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment') === 'map' ? 'map' : 'viewport';\n }\n if (this.layout.get('icon-pitch-alignment') === 'auto') {\n this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment');\n }\n\n if (this.layout.get('symbol-placement') === 'point') {\n const writingModes = this.layout.get('text-writing-mode');\n if (writingModes) {\n // remove duplicates, preserving order\n const deduped = [];\n for (const m of writingModes) {\n if (deduped.indexOf(m) < 0) deduped.push(m);\n }\n this.layout._values['text-writing-mode'] = deduped;\n } else {\n this.layout._values['text-writing-mode'] = ['horizontal'];\n }\n }\n\n this._setPaintOverrides();\n }\n\n getValueAndResolveTokens(name: any, feature: Feature, canonical: CanonicalTileID, availableImages: Array) {\n const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages);\n const unevaluated = this._unevaluatedLayout._values[name];\n if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) {\n return resolveTokens(feature.properties, value);\n }\n\n return value;\n }\n\n createBucket(parameters: BucketParameters) {\n return new SymbolBucket(parameters);\n }\n\n queryRadius(): number {\n return 0;\n }\n\n queryIntersectsFeature(): boolean {\n throw new Error('Should take a different path in FeatureIndex');\n }\n\n _setPaintOverrides() {\n for (const overridable of properties.paint.overridableProperties) {\n if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) {\n continue;\n }\n const overridden = this.paint.get(overridable as keyof SymbolPaintPropsPossiblyEvaluated) as PossiblyEvaluatedPropertyValue;\n const override = new FormatSectionOverride(overridden);\n const styleExpression = new StyleExpression(override, overridden.property.specification);\n let expression = null;\n if (overridden.value.kind === 'constant' || overridden.value.kind === 'source') {\n expression = new ZoomConstantExpression('source', styleExpression) as SourceExpression;\n } else {\n expression = new ZoomDependentExpression('composite',\n styleExpression,\n overridden.value.zoomStops);\n }\n this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overridden.property,\n expression,\n overridden.parameters);\n }\n }\n\n _handleOverridablePaintPropertyUpdate(name: string, oldValue: PropertyValue, newValue: PropertyValue): boolean {\n if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) {\n return false;\n }\n return SymbolStyleLayer.hasPaintOverride(this.layout, name);\n }\n\n static hasPaintOverride(layout: PossiblyEvaluated, propertyName: string): boolean {\n const textField = layout.get('text-field');\n const property = properties.paint.properties[propertyName];\n let hasOverrides = false;\n\n const checkSections = (sections) => {\n for (const section of sections) {\n if (property.overrides && property.overrides.hasOverride(section)) {\n hasOverrides = true;\n return;\n }\n }\n };\n\n if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) {\n checkSections(textField.value.value.sections);\n } else if (textField.value.kind === 'source') {\n\n const checkExpression = (expression: Expression) => {\n if (hasOverrides) return;\n\n if (expression instanceof Literal && typeOf(expression.value) === FormattedType) {\n const formatted: Formatted = (expression.value as any);\n checkSections(formatted.sections);\n } else if (expression instanceof FormatExpression) {\n checkSections(expression.sections);\n } else {\n expression.eachChild(checkExpression);\n }\n };\n\n const expr: ZoomConstantExpression<'source'> = (textField.value as any);\n if (expr._styleExpression) {\n checkExpression(expr._styleExpression.expression);\n }\n }\n\n return hasOverrides;\n }\n}\n\nexport type SymbolPadding = [number, number, number, number];\n\nexport function getIconPadding(layout: PossiblyEvaluated, feature: SymbolFeature, canonical: CanonicalTileID, pixelRatio = 1): SymbolPadding {\n // Support text-padding in addition to icon-padding? Unclear how to apply asymmetric text-padding to the radius for collision circles.\n const result = layout.get('icon-padding').evaluate(feature, {}, canonical);\n const values = result && result.values;\n\n return [\n values[0] * pixelRatio,\n values[1] * pixelRatio,\n values[2] * pixelRatio,\n values[3] * pixelRatio,\n ];\n}\n","/**\n * Replace tokens in a string template with values in an object\n *\n * @param properties - a key/value relationship between tokens and replacements\n * @param text - the template string\n * @returns the template with tokens replaced\n */\nexport function resolveTokens(\n properties: {\n readonly [x: string]: unknown;\n } | null,\n text: string\n): string {\n return text.replace(/{([^{}]+)}/g, (match, key: string) => {\n return properties && key in properties ? String(properties[key]) : '';\n });\n}\n","// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty,\n PossiblyEvaluatedPropertyValue,\n CrossFaded\n} from '../properties';\n\nimport type {Color, Formatted, Padding, ResolvedImage, VariableAnchorOffsetCollection} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type BackgroundPaintProps = {\n \"background-color\": DataConstantProperty,\n \"background-pattern\": CrossFadedProperty,\n \"background-opacity\": DataConstantProperty,\n};\n\nexport type BackgroundPaintPropsPossiblyEvaluated = {\n \"background-color\": Color,\n \"background-pattern\": CrossFaded,\n \"background-opacity\": number,\n};\n\nlet paint: Properties;\nconst getPaint = () => paint = paint || new Properties({\n \"background-color\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-color\"] as any as StylePropertySpecification),\n \"background-pattern\": new CrossFadedProperty(styleSpec[\"paint_background\"][\"background-pattern\"] as any as StylePropertySpecification),\n \"background-opacity\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-opacity\"] as any as StylePropertySpecification),\n});\n\nexport default ({ get paint() { return getPaint() } });","import {StyleLayer} from '../style_layer';\n\nimport properties, {BackgroundPaintPropsPossiblyEvaluated} from './background_style_layer_properties.g';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\n\nimport type {BackgroundPaintProps} from './background_style_layer_properties.g';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport class BackgroundStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n}\n","// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty,\n PossiblyEvaluatedPropertyValue,\n CrossFaded\n} from '../properties';\n\nimport type {Color, Formatted, Padding, ResolvedImage, VariableAnchorOffsetCollection} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type RasterPaintProps = {\n \"raster-opacity\": DataConstantProperty,\n \"raster-hue-rotate\": DataConstantProperty,\n \"raster-brightness-min\": DataConstantProperty,\n \"raster-brightness-max\": DataConstantProperty,\n \"raster-saturation\": DataConstantProperty,\n \"raster-contrast\": DataConstantProperty,\n \"raster-resampling\": DataConstantProperty<\"linear\" | \"nearest\">,\n \"raster-fade-duration\": DataConstantProperty,\n};\n\nexport type RasterPaintPropsPossiblyEvaluated = {\n \"raster-opacity\": number,\n \"raster-hue-rotate\": number,\n \"raster-brightness-min\": number,\n \"raster-brightness-max\": number,\n \"raster-saturation\": number,\n \"raster-contrast\": number,\n \"raster-resampling\": \"linear\" | \"nearest\",\n \"raster-fade-duration\": number,\n};\n\nlet paint: Properties;\nconst getPaint = () => paint = paint || new Properties({\n \"raster-opacity\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-opacity\"] as any as StylePropertySpecification),\n \"raster-hue-rotate\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-hue-rotate\"] as any as StylePropertySpecification),\n \"raster-brightness-min\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-min\"] as any as StylePropertySpecification),\n \"raster-brightness-max\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-max\"] as any as StylePropertySpecification),\n \"raster-saturation\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-saturation\"] as any as StylePropertySpecification),\n \"raster-contrast\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-contrast\"] as any as StylePropertySpecification),\n \"raster-resampling\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-resampling\"] as any as StylePropertySpecification),\n \"raster-fade-duration\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-fade-duration\"] as any as StylePropertySpecification),\n});\n\nexport default ({ get paint() { return getPaint() } });","import {StyleLayer} from '../style_layer';\n\nimport properties, {RasterPaintPropsPossiblyEvaluated} from './raster_style_layer_properties.g';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\n\nimport type {RasterPaintProps} from './raster_style_layer_properties.g';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport class RasterStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n}\n","import {StyleLayer} from '../style_layer';\nimport type {Map} from '../../ui/map';\nimport {mat4} from 'gl-matrix';\nimport {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n* Input arguments exposed by custom render function.\n*/\ntype CustomRenderMethodInput = {\n /**\n * This value represents the distance from the camera to the far clipping plane.\n * It is used in the calculation of the projection matrix to determine which objects are visible.\n * farZ should be larger than nearZ.\n */\n farZ: number;\n /**\n * This value represents the distance from the camera to the near clipping plane.\n * It is used in the calculation of the projection matrix to determine which objects are visible.\n * nearZ should be smaller than farZ.\n */\n nearZ: number;\n /** field of view of camera **/\n fov: number;\n /**\n * model view projection matrix\n * represents the matrix converting from world space to clip space\n * https://learnopengl.com/Getting-started/Coordinate-Systems\n * **/\n modelViewProjectionMatrix: mat4;\n /**\n * projection matrix\n * represents the matrix converting from view space to clip space\n * https://learnopengl.com/Getting-started/Coordinate-Systems\n */\n projectionMatrix: mat4;\n}\n\n/**\n * @param gl - The map's gl context.\n * @param matrix - The map's camera matrix. It projects spherical mercator\n * coordinates to gl clip space coordinates. The spherical mercator coordinate `[0, 0]` represents the\n * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When\n * the `renderingMode` is `\"3d\"`, the z coordinate is conformal. A box with identical x, y, and z\n * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate.fromLngLat}\n * can be used to project a `LngLat` to a mercator coordinate.\n * @param options - Argument object with additional render inputs like camera properties.\n */\ntype CustomRenderMethod = (gl: WebGLRenderingContext|WebGL2RenderingContext, matrix: mat4, options: CustomRenderMethodInput) => void;\n\n/**\n * Interface for custom style layers. This is a specification for\n * implementers to model: it is not an exported method or class.\n *\n * Custom layers allow a user to render directly into the map's GL context using the map's camera.\n * These layers can be added between any regular layers using {@link Map#addLayer}.\n *\n * Custom layers must have a unique `id` and must have the `type` of `\"custom\"`.\n * They must implement `render` and may implement `prerender`, `onAdd` and `onRemove`.\n * They can trigger rendering using {@link Map#triggerRepaint}\n * and they should appropriately handle {@link MapContextEvent} with `webglcontextlost` and `webglcontextrestored`.\n *\n * The `renderingMode` property controls whether the layer is treated as a `\"2d\"` or `\"3d\"` map layer. Use:\n *\n * - `\"renderingMode\": \"3d\"` to use the depth buffer and share it with other layers\n * - `\"renderingMode\": \"2d\"` to add a layer with no depth. If you need to use the depth buffer for a `\"2d\"` layer you must use an offscreen\n * framebuffer and {@link CustomLayerInterface#prerender}\n *\n * @example\n * Custom layer implemented as ES6 class\n * ```ts\n * class NullIslandLayer {\n * constructor() {\n * this.id = 'null-island';\n * this.type = 'custom';\n * this.renderingMode = '2d';\n * }\n *\n * onAdd(map, gl) {\n * const vertexSource = `\n * uniform mat4 u_matrix;\n * void main() {\n * gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0);\n * gl_PointSize = 20.0;\n * }`;\n *\n * const fragmentSource = `\n * void main() {\n * fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n * }`;\n *\n * const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n * gl.shaderSource(vertexShader, vertexSource);\n * gl.compileShader(vertexShader);\n * const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n * gl.shaderSource(fragmentShader, fragmentSource);\n * gl.compileShader(fragmentShader);\n *\n * this.program = gl.createProgram();\n * gl.attachShader(this.program, vertexShader);\n * gl.attachShader(this.program, fragmentShader);\n * gl.linkProgram(this.program);\n * }\n *\n * render(gl, matrix) {\n * gl.useProgram(this.program);\n * gl.uniformMatrix4fv(gl.getUniformLocation(this.program, \"u_matrix\"), false, matrix);\n * gl.drawArrays(gl.POINTS, 0, 1);\n * }\n * }\n *\n * map.on('load', () => {\n * map.addLayer(new NullIslandLayer());\n * });\n * ```\n */\nexport interface CustomLayerInterface {\n /**\n * A unique layer id.\n */\n id: string;\n /**\n * The layer's type. Must be `\"custom\"`.\n */\n type: 'custom';\n /**\n * Either `\"2d\"` or `\"3d\"`. Defaults to `\"2d\"`.\n */\n renderingMode?: '2d' | '3d';\n /**\n * Called during a render frame allowing the layer to draw into the GL context.\n *\n * The layer can assume blending and depth state is set to allow the layer to properly\n * blend and clip other layers. The layer cannot make any other assumptions about the\n * current GL state.\n *\n * If the layer needs to render to a texture, it should implement the `prerender` method\n * to do this and only use the `render` method for drawing directly into the main framebuffer.\n *\n * The blend function is set to `gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. This expects\n * colors to be provided in premultiplied alpha form where the `r`, `g` and `b` values are already\n * multiplied by the `a` value. If you are unable to provide colors in premultiplied form you\n * may want to change the blend function to\n * `gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`.\n */\n render: CustomRenderMethod;\n /**\n * Optional method called during a render frame to allow a layer to prepare resources or render into a texture.\n *\n * The layer cannot make any assumptions about the current GL state and must bind a framebuffer before rendering.\n */\n prerender?: CustomRenderMethod;\n /**\n * Optional method called when the layer has been added to the Map with {@link Map#addLayer}. This\n * gives the layer a chance to initialize gl resources and register event listeners.\n *\n * @param map - The Map this custom layer was just added to.\n * @param gl - The gl context for the map.\n */\n onAdd?(map: Map, gl: WebGLRenderingContext | WebGL2RenderingContext): void;\n /**\n * Optional method called when the layer has been removed from the Map with {@link Map#removeLayer}. This\n * gives the layer a chance to clean up gl resources and event listeners.\n *\n * @param map - The Map this custom layer was just added to.\n * @param gl - The gl context for the map.\n */\n onRemove?(map: Map, gl: WebGLRenderingContext | WebGL2RenderingContext): void;\n}\n\nexport function validateCustomStyleLayer(layerObject: CustomLayerInterface) {\n const errors = [];\n const id = layerObject.id;\n\n if (id === undefined) {\n errors.push({\n message: `layers.${id}: missing required property \"id\"`\n });\n }\n\n if (layerObject.render === undefined) {\n errors.push({\n message: `layers.${id}: missing required method \"render\"`\n });\n }\n\n if (layerObject.renderingMode &&\n layerObject.renderingMode !== '2d' &&\n layerObject.renderingMode !== '3d') {\n errors.push({\n message: `layers.${id}: property \"renderingMode\" must be either \"2d\" or \"3d\"`\n });\n }\n\n return errors;\n}\n\nexport class CustomStyleLayer extends StyleLayer {\n\n implementation: CustomLayerInterface;\n\n constructor(implementation: CustomLayerInterface) {\n super(implementation, {});\n this.implementation = implementation;\n }\n\n is3D() {\n return this.implementation.renderingMode === '3d';\n }\n\n hasOffscreenPass() {\n return this.implementation.prerender !== undefined;\n }\n\n recalculate() {}\n updateTransitions() {}\n hasTransition() { return false; }\n\n serialize(): LayerSpecification {\n throw new Error('Custom layers cannot be serialized');\n }\n\n onAdd = (map: Map) => {\n if (this.implementation.onAdd) {\n this.implementation.onAdd(map, map.painter.context.gl);\n }\n };\n\n onRemove = (map: Map) => {\n if (this.implementation.onRemove) {\n this.implementation.onRemove(map, map.painter.context.gl);\n }\n };\n}\n","import {CircleStyleLayer} from './style_layer/circle_style_layer';\nimport {HeatmapStyleLayer} from './style_layer/heatmap_style_layer';\nimport {HillshadeStyleLayer} from './style_layer/hillshade_style_layer';\nimport {FillStyleLayer} from './style_layer/fill_style_layer';\nimport {FillExtrusionStyleLayer} from './style_layer/fill_extrusion_style_layer';\nimport {LineStyleLayer} from './style_layer/line_style_layer';\nimport {SymbolStyleLayer} from './style_layer/symbol_style_layer';\nimport {BackgroundStyleLayer} from './style_layer/background_style_layer';\nimport {RasterStyleLayer} from './style_layer/raster_style_layer';\nimport {CustomStyleLayer, type CustomLayerInterface} from './style_layer/custom_style_layer';\n\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport function createStyleLayer(layer: LayerSpecification | CustomLayerInterface) {\n if (layer.type === 'custom') {\n return new CustomStyleLayer(layer);\n }\n switch (layer.type) {\n case 'background':\n return new BackgroundStyleLayer(layer);\n case 'circle':\n return new CircleStyleLayer(layer);\n case 'fill':\n return new FillStyleLayer(layer);\n case 'fill-extrusion':\n return new FillExtrusionStyleLayer(layer);\n case 'heatmap':\n return new HeatmapStyleLayer(layer);\n case 'hillshade':\n return new HillshadeStyleLayer(layer);\n case 'line':\n return new LineStyleLayer(layer);\n case 'raster':\n return new RasterStyleLayer(layer);\n case 'symbol':\n return new SymbolStyleLayer(layer);\n }\n}\n\n","import type {SpriteSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * Takes a SpriteSpecification value and returns it in its array form. If `undefined` is passed as an input value, an\n * empty array is returned.\n * duplicated entries with identical id/url will be removed in returned array\n * @param sprite - optional sprite to coerce\n * @returns an empty array in case `undefined` is passed; id-url pairs otherwise\n */\nexport function coerceSpriteToArray(sprite?: SpriteSpecification): {id: string; url: string}[] {\n const resultArray: {id: string; url: string}[] = [];\n\n if (typeof sprite === 'string') {\n resultArray.push({id: 'default', url: sprite});\n } else if (sprite && sprite.length > 0) {\n const dedupArray: string[] = [];\n for (const {id, url} of sprite) {\n const key = `${id}${url}`;\n if (dedupArray.indexOf(key) === -1) {\n dedupArray.push(key);\n resultArray.push({id, url});\n }\n }\n }\n\n return resultArray;\n\n}\n","import {GetResourceResponse, getJSON} from '../util/ajax';\nimport {ImageRequest} from '../util/image_request';\nimport {ResourceType} from '../util/request_manager';\n\nimport {browser} from '../util/browser';\nimport {coerceSpriteToArray} from '../util/style';\n\nimport type {SpriteSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {SpriteJSON, StyleImage} from './style_image';\nimport type {RequestManager} from '../util/request_manager';\n\nexport type LoadSpriteResult = {\n [spriteName: string]: {\n [id: string]: StyleImage;\n };\n}\n\nexport function normalizeSpriteURL(url: string, format: string, extension: string): string {\n const split = url.split('?');\n split[0] += `${format}${extension}`;\n return split.join('?');\n}\n\nexport async function loadSprite(\n originalSprite: SpriteSpecification,\n requestManager: RequestManager,\n pixelRatio: number,\n abortController: AbortController,\n): Promise {\n const spriteArray = coerceSpriteToArray(originalSprite);\n const format = pixelRatio > 1 ? '@2x' : '';\n\n const jsonsMap: {[id: string]: Promise>} = {};\n const imagesMap: {[id: string]: Promise>} = {};\n\n for (const {id, url} of spriteArray) {\n const jsonRequestParameters = requestManager.transformRequest(normalizeSpriteURL(url, format, '.json'), ResourceType.SpriteJSON);\n jsonsMap[id] = getJSON(jsonRequestParameters, abortController);\n\n const imageRequestParameters = requestManager.transformRequest(normalizeSpriteURL(url, format, '.png'), ResourceType.SpriteImage);\n imagesMap[id] = ImageRequest.getImage(imageRequestParameters, abortController);\n }\n\n await Promise.all([...Object.values(jsonsMap), ...Object.values(imagesMap)]);\n return doOnceCompleted(jsonsMap, imagesMap);\n}\n\n/**\n * @param jsonsMap - JSON data map\n * @param imagesMap - image data map\n */\nasync function doOnceCompleted(\n jsonsMap:{[id: string]: Promise>},\n imagesMap:{[id: string]: Promise>}): Promise {\n\n const result = {} as {[spriteName: string]: {[id: string]: StyleImage}};\n for (const spriteName in jsonsMap) {\n result[spriteName] = {};\n\n const context = browser.getImageCanvasContext((await imagesMap[spriteName]).data);\n const json = (await jsonsMap[spriteName]).data;\n\n for (const id in json) {\n const {width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight} = json[id];\n const spriteData = {width, height, x, y, context};\n result[spriteName][id] = {data: null, pixelRatio, sdf, stretchX, stretchY, content, textFitWidth, textFitHeight, spriteData};\n }\n }\n\n return result;\n}\n","import type {Context} from '../gl/context';\nimport type {RGBAImage, AlphaImage} from '../util/image';\nimport {isImageBitmap} from '../util/util';\n\nexport type TextureFormat = WebGLRenderingContextBase['RGBA'] | WebGLRenderingContextBase['ALPHA'];\nexport type TextureFilter = WebGLRenderingContextBase['LINEAR'] | WebGLRenderingContextBase['LINEAR_MIPMAP_NEAREST'] | WebGLRenderingContextBase['NEAREST'];\nexport type TextureWrap = WebGLRenderingContextBase['REPEAT'] | WebGLRenderingContextBase['CLAMP_TO_EDGE'] | WebGLRenderingContextBase['MIRRORED_REPEAT'];\n\ntype EmptyImage = {\n width: number;\n height: number;\n data: null;\n};\n\ntype DataTextureImage = RGBAImage | AlphaImage | EmptyImage;\nexport type TextureImage = TexImageSource | DataTextureImage;\n\n/**\n * @internal\n * A `Texture` GL related object\n */\nexport class Texture {\n context: Context;\n size: [number, number];\n texture: WebGLTexture;\n format: TextureFormat;\n filter: TextureFilter;\n wrap: TextureWrap;\n useMipmap: boolean;\n\n constructor(context: Context, image: TextureImage, format: TextureFormat, options?: {\n premultiply?: boolean;\n useMipmap?: boolean;\n } | null) {\n this.context = context;\n this.format = format;\n this.texture = context.gl.createTexture();\n this.update(image, options);\n }\n\n update(image: TextureImage, options?: {\n premultiply?: boolean;\n useMipmap?: boolean;\n } | null, position?: {\n x: number;\n y: number;\n }) {\n const {width, height} = image as {width: number; height: number};\n const resize = (!this.size || this.size[0] !== width || this.size[1] !== height) && !position;\n const {context} = this;\n const {gl} = context;\n\n this.useMipmap = Boolean(options && options.useMipmap);\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n context.pixelStoreUnpackFlipY.set(false);\n context.pixelStoreUnpack.set(1);\n context.pixelStoreUnpackPremultiplyAlpha.set(this.format === gl.RGBA && (!options || options.premultiply !== false));\n\n if (resize) {\n this.size = [width, height];\n\n if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || isImageBitmap(image)) {\n gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, gl.UNSIGNED_BYTE, image);\n } else {\n gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl.UNSIGNED_BYTE, (image as DataTextureImage).data);\n }\n\n } else {\n const {x, y} = position || {x: 0, y: 0};\n if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || isImageBitmap(image)) {\n gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image);\n } else {\n gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, (image as DataTextureImage).data);\n }\n }\n\n if (this.useMipmap && this.isSizePowerOfTwo()) {\n gl.generateMipmap(gl.TEXTURE_2D);\n }\n }\n\n bind(filter: TextureFilter, wrap: TextureWrap, minFilter?: TextureFilter | null) {\n const {context} = this;\n const {gl} = context;\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n if (minFilter === gl.LINEAR_MIPMAP_NEAREST && !this.isSizePowerOfTwo()) {\n minFilter = gl.LINEAR;\n }\n\n if (filter !== this.filter) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter || filter);\n this.filter = filter;\n }\n\n if (wrap !== this.wrap) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);\n this.wrap = wrap;\n }\n }\n\n isSizePowerOfTwo() {\n return this.size[0] === this.size[1] && (Math.log(this.size[0]) / Math.LN2) % 1 === 0;\n }\n\n destroy() {\n const {gl} = this.context;\n gl.deleteTexture(this.texture);\n this.texture = null;\n }\n}\n","import {RGBAImage} from '../util/image';\n\nimport type {Map} from '../ui/map';\n\nexport type SpriteJSON = {[id: string]: StyleImageMetadata & {\n width: number;\n height: number;\n x: number;\n y: number;\n};}\n\n/**\n * The sprite data\n */\nexport type SpriteOnDemandStyleImage = {\n width: number;\n height: number;\n x: number;\n y: number;\n context: CanvasRenderingContext2D;\n};\n\n/**\n * The style's image metadata\n */\nexport type StyleImageData = {\n data: RGBAImage;\n version?: number;\n hasRenderCallback?: boolean;\n userImage?: StyleImageInterface;\n spriteData?: SpriteOnDemandStyleImage;\n};\n\n/**\n * Enumeration of possible values for StyleImageMetadata.textFitWidth and textFitHeight.\n */\nexport const enum TextFit {\n /**\n * The image will be resized on the specified axis to tightly fit the content rectangle to target text.\n * This is the same as not being defined.\n */\n stretchOrShrink = 'stretchOrShrink',\n /**\n * The image will be resized on the specified axis to fit the content rectangle to the target text, but will not\n * fall below the aspect ratio of the original content rectangle if the other axis is set to proportional.\n */\n stretchOnly = 'stretchOnly',\n /**\n * The image will be resized on the specified axis to fit the content rectangle to the target text and\n * will resize the other axis to maintain the aspect ratio of the content rectangle.\n */\n proportional = 'proportional'\n}\n\n/**\n * The style's image metadata\n */\nexport type StyleImageMetadata = {\n /**\n * The ratio of pixels in the image to physical pixels on the screen\n */\n pixelRatio: number;\n /**\n * Whether the image should be interpreted as an SDF image\n */\n sdf: boolean;\n /**\n * If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched horizontally.\n */\n stretchX?: Array<[number, number]>;\n /**\n * If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched vertically.\n */\n stretchY?: Array<[number, number]>;\n /**\n * If `icon-text-fit` is used in a layer with this image, this option defines the part of the image that can be covered by the content in `text-field`.\n */\n content?: [number, number, number, number];\n /**\n * If `icon-text-fit` is used in a layer with this image, this option defines constraints on the horizontal scaling of the image.\n */\n textFitWidth?: TextFit;\n /**\n * If `icon-text-fit` is used in a layer with this image, this option defines constraints on the vertical scaling of the image.\n */\n textFitHeight?: TextFit;\n};\n\n/**\n * the style's image, including data and metedata\n */\nexport type StyleImage = StyleImageData & StyleImageMetadata;\n\n/**\n * Interface for dynamically generated style images. This is a specification for\n * implementers to model: it is not an exported method or class.\n *\n * Images implementing this interface can be redrawn for every frame. They can be used to animate\n * icons and patterns or make them respond to user input. Style images can implement a\n * {@link StyleImageInterface#render} method. The method is called every frame and\n * can be used to update the image.\n *\n * @see [Add an animated icon to the map.](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-animated/)\n *\n * @example\n * ```ts\n * let flashingSquare = {\n * width: 64,\n * height: 64,\n * data: new Uint8Array(64 * 64 * 4),\n *\n * onAdd: function(map) {\n * this.map = map;\n * },\n *\n * render: function() {\n * // keep repainting while the icon is on the map\n * this.map.triggerRepaint();\n *\n * // alternate between black and white based on the time\n * let value = Math.round(Date.now() / 1000) % 2 === 0 ? 255 : 0;\n *\n * // check if image needs to be changed\n * if (value !== this.previousValue) {\n * this.previousValue = value;\n *\n * let bytesPerPixel = 4;\n * for (let x = 0; x < this.width; x++) {\n * for (let y = 0; y < this.height; y++) {\n * let offset = (y * this.width + x) * bytesPerPixel;\n * this.data[offset + 0] = value;\n * this.data[offset + 1] = value;\n * this.data[offset + 2] = value;\n * this.data[offset + 3] = 255;\n * }\n * }\n *\n * // return true to indicate that the image changed\n * return true;\n * }\n * }\n * }\n *\n * map.addImage('flashing_square', flashingSquare);\n * ```\n */\n\nexport interface StyleImageInterface {\n width: number;\n height: number;\n data: Uint8Array | Uint8ClampedArray;\n /**\n * This method is called once before every frame where the icon will be used.\n * The method can optionally update the image's `data` member with a new image.\n *\n * If the method updates the image it must return `true` to commit the change.\n * If the method returns `false` or nothing the image is assumed to not have changed.\n *\n * If updates are infrequent it maybe easier to use {@link Map#updateImage} to update\n * the image instead of implementing this method.\n *\n * @returns `true` if this method updated the image. `false` if the image was not changed.\n */\n render?: () => boolean;\n /**\n * Optional method called when the layer has been added to the Map with {@link Map#addImage}.\n *\n * @param map - The Map this custom layer was just added to.\n */\n onAdd?: (map: Map, id: string) => void;\n /**\n * Optional method called when the icon is removed from the map with {@link Map#removeImage}.\n * This gives the image a chance to clean up resources and event listeners.\n */\n onRemove?: () => void;\n}\n\nexport function renderStyleImage(image: StyleImage) {\n const {userImage} = image;\n if (userImage && userImage.render) {\n const updated = userImage.render();\n if (updated) {\n image.data.replace(new Uint8Array(userImage.data.buffer));\n return true;\n }\n }\n return false;\n}\n","/* eslint-disable key-spacing */\nimport potpack from 'potpack';\n\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport {RGBAImage} from '../util/image';\nimport {ImagePosition} from './image_atlas';\nimport {Texture} from './texture';\nimport {renderStyleImage} from '../style/style_image';\nimport {warnOnce} from '../util/util';\n\nimport type {StyleImage} from '../style/style_image';\nimport type {Context} from '../gl/context';\nimport type {PotpackBox} from 'potpack';\nimport type {GetImagesResponse} from '../util/actor_messages';\n\ntype Pattern = {\n bin: PotpackBox;\n position: ImagePosition;\n};\n\n/**\n * When copied into the atlas texture, image data is padded by one pixel on each side. Icon\n * images are padded with fully transparent pixels, while pattern images are padded with a\n * copy of the image data wrapped from the opposite side. In both cases, this ensures the\n * correct behavior of GL_LINEAR texture sampling mode.\n */\nconst padding = 1;\n\n/**\n * ImageManager does three things:\n *\n * 1. Tracks requests for icon images from tile workers and sends responses when the requests are fulfilled.\n * 2. Builds a texture atlas for pattern images.\n * 3. Rerenders renderable images once per frame\n *\n * These are disparate responsibilities and should eventually be handled by different classes. When we implement\n * data-driven support for `*-pattern`, we'll likely use per-bucket pattern atlases, and that would be a good time\n * to refactor this.\n*/\nexport class ImageManager extends Evented {\n images: {[_: string]: StyleImage};\n updatedImages: {[_: string]: boolean};\n callbackDispatchedThisFrame: {[_: string]: boolean};\n loaded: boolean;\n /**\n * This is used to track requests for images that are not yet available. When the image is loaded,\n * the requestors will be notified.\n */\n requestors: Array<{\n ids: Array;\n promiseResolve: (value: GetImagesResponse) => void;\n }>;\n\n patterns: {[_: string]: Pattern};\n atlasImage: RGBAImage;\n atlasTexture: Texture;\n dirty: boolean;\n\n constructor() {\n super();\n this.images = {};\n this.updatedImages = {};\n this.callbackDispatchedThisFrame = {};\n this.loaded = false;\n this.requestors = [];\n\n this.patterns = {};\n this.atlasImage = new RGBAImage({width: 1, height: 1});\n this.dirty = true;\n }\n\n isLoaded() {\n return this.loaded;\n }\n\n setLoaded(loaded: boolean) {\n if (this.loaded === loaded) {\n return;\n }\n\n this.loaded = loaded;\n\n if (loaded) {\n for (const {ids, promiseResolve} of this.requestors) {\n promiseResolve(this._getImagesForIds(ids));\n }\n this.requestors = [];\n }\n }\n\n getImage(id: string): StyleImage {\n const image = this.images[id];\n\n // Extract sprite image data on demand\n if (image && !image.data && image.spriteData) {\n const spriteData = image.spriteData;\n image.data = new RGBAImage({\n width: spriteData.width,\n height: spriteData.height\n }, spriteData.context.getImageData(\n spriteData.x,\n spriteData.y,\n spriteData.width,\n spriteData.height).data);\n image.spriteData = null;\n }\n\n return image;\n }\n\n addImage(id: string, image: StyleImage) {\n if (this.images[id]) throw new Error(`Image id ${id} already exist, use updateImage instead`);\n if (this._validate(id, image)) {\n this.images[id] = image;\n }\n }\n\n _validate(id: string, image: StyleImage) {\n let valid = true;\n const data = image.data || image.spriteData;\n if (!this._validateStretch(image.stretchX, data && data.width)) {\n this.fire(new ErrorEvent(new Error(`Image \"${id}\" has invalid \"stretchX\" value`)));\n valid = false;\n }\n if (!this._validateStretch(image.stretchY, data && data.height)) {\n this.fire(new ErrorEvent(new Error(`Image \"${id}\" has invalid \"stretchY\" value`)));\n valid = false;\n }\n if (!this._validateContent(image.content, image)) {\n this.fire(new ErrorEvent(new Error(`Image \"${id}\" has invalid \"content\" value`)));\n valid = false;\n }\n return valid;\n }\n\n _validateStretch(stretch: Array<[number, number]>, size: number) {\n if (!stretch) return true;\n let last = 0;\n for (const part of stretch) {\n if (part[0] < last || part[1] < part[0] || size < part[1]) return false;\n last = part[1];\n }\n return true;\n }\n\n _validateContent(content: [number, number, number, number], image: StyleImage) {\n if (!content) return true;\n if (content.length !== 4) return false;\n const spriteData = image.spriteData;\n const width = (spriteData && spriteData.width) || image.data.width;\n const height = (spriteData && spriteData.height) || image.data.height;\n if (content[0] < 0 || width < content[0]) return false;\n if (content[1] < 0 || height < content[1]) return false;\n if (content[2] < 0 || width < content[2]) return false;\n if (content[3] < 0 || height < content[3]) return false;\n if (content[2] < content[0]) return false;\n if (content[3] < content[1]) return false;\n return true;\n }\n\n updateImage(id: string, image: StyleImage, validate = true) {\n const oldImage = this.getImage(id);\n if (validate && (oldImage.data.width !== image.data.width || oldImage.data.height !== image.data.height)) {\n throw new Error(`size mismatch between old image (${oldImage.data.width}x${oldImage.data.height}) and new image (${image.data.width}x${image.data.height}).`);\n }\n image.version = oldImage.version + 1;\n this.images[id] = image;\n this.updatedImages[id] = true;\n }\n\n removeImage(id: string) {\n const image = this.images[id];\n delete this.images[id];\n delete this.patterns[id];\n\n if (image.userImage && image.userImage.onRemove) {\n image.userImage.onRemove();\n }\n }\n\n listImages(): Array {\n return Object.keys(this.images);\n }\n\n getImages(ids: Array): Promise {\n return new Promise((resolve, _reject) => {\n // If the sprite has been loaded, or if all the icon dependencies are already present\n // (i.e. if they've been added via runtime styling), then notify the requestor immediately.\n // Otherwise, delay notification until the sprite is loaded. At that point, if any of the\n // dependencies are still unavailable, we'll just assume they are permanently missing.\n let hasAllDependencies = true;\n if (!this.isLoaded()) {\n for (const id of ids) {\n if (!this.images[id]) {\n hasAllDependencies = false;\n }\n }\n }\n if (this.isLoaded() || hasAllDependencies) {\n resolve(this._getImagesForIds(ids));\n } else {\n this.requestors.push({ids, promiseResolve: resolve});\n }\n });\n }\n\n _getImagesForIds(ids: Array): GetImagesResponse {\n const response: GetImagesResponse = {};\n\n for (const id of ids) {\n let image = this.getImage(id);\n\n if (!image) {\n this.fire(new Event('styleimagemissing', {id}));\n //Try to acquire image again in case styleimagemissing has populated it\n image = this.getImage(id);\n }\n\n if (image) {\n // Clone the image so that our own copy of its ArrayBuffer doesn't get transferred.\n response[id] = {\n data: image.data.clone(),\n pixelRatio: image.pixelRatio,\n sdf: image.sdf,\n version: image.version,\n stretchX: image.stretchX,\n stretchY: image.stretchY,\n content: image.content,\n textFitWidth: image.textFitWidth,\n textFitHeight: image.textFitHeight,\n hasRenderCallback: Boolean(image.userImage && image.userImage.render)\n };\n } else {\n warnOnce(`Image \"${id}\" could not be loaded. Please make sure you have added the image with map.addImage() or a \"sprite\" property in your style. You can provide missing images by listening for the \"styleimagemissing\" map event.`);\n }\n }\n return response;\n }\n\n // Pattern stuff\n\n getPixelSize() {\n const {width, height} = this.atlasImage;\n return {width, height};\n }\n\n getPattern(id: string): ImagePosition {\n const pattern = this.patterns[id];\n\n const image = this.getImage(id);\n if (!image) {\n return null;\n }\n\n if (pattern && pattern.position.version === image.version) {\n return pattern.position;\n }\n\n if (!pattern) {\n const w = image.data.width + padding * 2;\n const h = image.data.height + padding * 2;\n const bin = {w, h, x: 0, y: 0};\n const position = new ImagePosition(bin, image);\n this.patterns[id] = {bin, position};\n } else {\n pattern.position.version = image.version;\n }\n\n this._updatePatternAtlas();\n\n return this.patterns[id].position;\n }\n\n bind(context: Context) {\n const gl = context.gl;\n if (!this.atlasTexture) {\n this.atlasTexture = new Texture(context, this.atlasImage, gl.RGBA);\n } else if (this.dirty) {\n this.atlasTexture.update(this.atlasImage);\n this.dirty = false;\n }\n\n this.atlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n }\n\n _updatePatternAtlas() {\n const bins = [];\n for (const id in this.patterns) {\n bins.push(this.patterns[id].bin);\n }\n\n const {w, h} = potpack(bins);\n\n const dst = this.atlasImage;\n dst.resize({width: w || 1, height: h || 1});\n\n for (const id in this.patterns) {\n const {bin} = this.patterns[id];\n const x = bin.x + padding;\n const y = bin.y + padding;\n const src = this.getImage(id).data;\n const w = src.width;\n const h = src.height;\n\n RGBAImage.copy(src, dst, {x: 0, y: 0}, {x, y}, {width: w, height: h});\n\n // Add 1 pixel wrapped padding on each side of the image.\n RGBAImage.copy(src, dst, {x: 0, y: h - 1}, {x, y: y - 1}, {width: w, height: 1}); // T\n RGBAImage.copy(src, dst, {x: 0, y: 0}, {x, y: y + h}, {width: w, height: 1}); // B\n RGBAImage.copy(src, dst, {x: w - 1, y: 0}, {x: x - 1, y}, {width: 1, height: h}); // L\n RGBAImage.copy(src, dst, {x: 0, y: 0}, {x: x + w, y}, {width: 1, height: h}); // R\n }\n\n this.dirty = true;\n }\n\n beginFrame() {\n this.callbackDispatchedThisFrame = {};\n }\n\n dispatchRenderCallbacks(ids: Array) {\n for (const id of ids) {\n\n // the callback for the image was already dispatched for a different frame\n if (this.callbackDispatchedThisFrame[id]) continue;\n this.callbackDispatchedThisFrame[id] = true;\n\n const image = this.getImage(id);\n if (!image) warnOnce(`Image with ID: \"${id}\" was not found`);\n\n const updated = renderStyleImage(image);\n if (updated) {\n this.updateImage(id, image);\n }\n }\n }\n}\n","const INF = 1e20;\n\nexport default class TinySDF {\n constructor({\n fontSize = 24,\n buffer = 3,\n radius = 8,\n cutoff = 0.25,\n fontFamily = 'sans-serif',\n fontWeight = 'normal',\n fontStyle = 'normal'\n } = {}) {\n this.buffer = buffer;\n this.cutoff = cutoff;\n this.radius = radius;\n\n // make the canvas size big enough to both have the specified buffer around the glyph\n // for \"halo\", and account for some glyphs possibly being larger than their font size\n const size = this.size = fontSize + buffer * 4;\n\n const canvas = this._createCanvas(size);\n const ctx = this.ctx = canvas.getContext('2d', {willReadFrequently: true});\n ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;\n\n ctx.textBaseline = 'alphabetic';\n ctx.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment\n ctx.fillStyle = 'black';\n\n // temporary arrays for the distance transform\n this.gridOuter = new Float64Array(size * size);\n this.gridInner = new Float64Array(size * size);\n this.f = new Float64Array(size);\n this.z = new Float64Array(size + 1);\n this.v = new Uint16Array(size);\n }\n\n _createCanvas(size) {\n const canvas = document.createElement('canvas');\n canvas.width = canvas.height = size;\n return canvas;\n }\n\n draw(char) {\n const {\n width: glyphAdvance,\n actualBoundingBoxAscent,\n actualBoundingBoxDescent,\n actualBoundingBoxLeft,\n actualBoundingBoxRight\n } = this.ctx.measureText(char);\n\n // The integer/pixel part of the top alignment is encoded in metrics.glyphTop\n // The remainder is implicitly encoded in the rasterization\n const glyphTop = Math.ceil(actualBoundingBoxAscent);\n const glyphLeft = 0;\n\n // If the glyph overflows the canvas size, it will be clipped at the bottom/right\n const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight - actualBoundingBoxLeft)));\n const glyphHeight = Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent));\n\n const width = glyphWidth + 2 * this.buffer;\n const height = glyphHeight + 2 * this.buffer;\n\n const len = Math.max(width * height, 0);\n const data = new Uint8ClampedArray(len);\n const glyph = {data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance};\n if (glyphWidth === 0 || glyphHeight === 0) return glyph;\n\n const {ctx, buffer, gridInner, gridOuter} = this;\n ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight);\n ctx.fillText(char, buffer, buffer + glyphTop);\n const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight);\n\n // Initialize grids outside the glyph range to alpha 0\n gridOuter.fill(INF, 0, len);\n gridInner.fill(0, 0, len);\n\n for (let y = 0; y < glyphHeight; y++) {\n for (let x = 0; x < glyphWidth; x++) {\n const a = imgData.data[4 * (y * glyphWidth + x) + 3] / 255; // alpha value\n if (a === 0) continue; // empty pixels\n\n const j = (y + buffer) * width + x + buffer;\n\n if (a === 1) { // fully drawn pixels\n gridOuter[j] = 0;\n gridInner[j] = INF;\n\n } else { // aliased pixels\n const d = 0.5 - a;\n gridOuter[j] = d > 0 ? d * d : 0;\n gridInner[j] = d < 0 ? d * d : 0;\n }\n }\n }\n\n edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z);\n edt(gridInner, buffer, buffer, glyphWidth, glyphHeight, width, this.f, this.v, this.z);\n\n for (let i = 0; i < len; i++) {\n const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]);\n data[i] = Math.round(255 - 255 * (d / this.radius + this.cutoff));\n }\n\n return glyph;\n }\n}\n\n// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf\nfunction edt(data, x0, y0, width, height, gridSize, f, v, z) {\n for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z);\n for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z);\n}\n\n// 1D squared distance transform\nfunction edt1d(grid, offset, stride, length, f, v, z) {\n v[0] = 0;\n z[0] = -INF;\n z[1] = INF;\n f[0] = grid[offset];\n\n for (let q = 1, k = 0, s = 0; q < length; q++) {\n f[q] = grid[offset + q * stride];\n const q2 = q * q;\n do {\n const r = v[k];\n s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2;\n } while (s <= z[k] && --k > -1);\n\n k++;\n v[k] = q;\n z[k] = s;\n z[k + 1] = INF;\n }\n\n for (let q = 0, k = 0; q < length; q++) {\n while (z[k + 1] < q) k++;\n const r = v[k];\n const qr = q - r;\n grid[offset + q * stride] = f[r] + qr * qr;\n }\n}\n","import {loadGlyphRange} from '../style/load_glyph_range';\n\nimport TinySDF from '@mapbox/tiny-sdf';\nimport {AlphaImage} from '../util/image';\n\nimport type {StyleGlyph} from '../style/style_glyph';\nimport type {RequestManager} from '../util/request_manager';\nimport type {GetGlyphsResponse} from '../util/actor_messages';\n\ntype Entry = {\n // null means we've requested the range, but the glyph wasn't included in the result.\n glyphs: {\n [id: number]: StyleGlyph | null;\n };\n requests: {\n [range: number]: Promise<{[_: number]: StyleGlyph | null}>;\n };\n ranges: {\n [range: number]: boolean | null;\n };\n tinySDF?: TinySDF;\n};\n\nexport class GlyphManager {\n requestManager: RequestManager;\n localIdeographFontFamily: string | false;\n entries: {[stack: string]: Entry};\n url: string;\n\n // exposed as statics to enable stubbing in unit tests\n static loadGlyphRange = loadGlyphRange;\n static TinySDF = TinySDF;\n\n constructor(requestManager: RequestManager, localIdeographFontFamily?: string | false) {\n this.requestManager = requestManager;\n this.localIdeographFontFamily = localIdeographFontFamily;\n this.entries = {};\n }\n\n setURL(url?: string | null) {\n this.url = url;\n }\n\n async getGlyphs(glyphs: {[stack: string]: Array}): Promise {\n const glyphsPromises: Promise<{stack: string; id: number; glyph: StyleGlyph}>[] = [];\n\n for (const stack in glyphs) {\n for (const id of glyphs[stack]) {\n glyphsPromises.push(this._getAndCacheGlyphsPromise(stack, id));\n }\n }\n\n const updatedGlyphs = await Promise.all(glyphsPromises);\n\n const result: GetGlyphsResponse = {};\n\n for (const {stack, id, glyph} of updatedGlyphs) {\n if (!result[stack]) {\n result[stack] = {};\n }\n // Clone the glyph so that our own copy of its ArrayBuffer doesn't get transferred.\n result[stack][id] = glyph && {\n id: glyph.id,\n bitmap: glyph.bitmap.clone(),\n metrics: glyph.metrics\n };\n }\n\n return result;\n }\n\n async _getAndCacheGlyphsPromise(stack: string, id: number): Promise<{stack: string; id: number; glyph: StyleGlyph}> {\n let entry = this.entries[stack];\n if (!entry) {\n entry = this.entries[stack] = {\n glyphs: {},\n requests: {},\n ranges: {}\n };\n }\n\n let glyph = entry.glyphs[id];\n if (glyph !== undefined) {\n return {stack, id, glyph};\n }\n\n glyph = this._tinySDF(entry, stack, id);\n if (glyph) {\n entry.glyphs[id] = glyph;\n return {stack, id, glyph};\n }\n\n const range = Math.floor(id / 256);\n if (range * 256 > 65535) {\n throw new Error('glyphs > 65535 not supported');\n }\n\n if (entry.ranges[range]) {\n return {stack, id, glyph};\n }\n\n if (!this.url) {\n throw new Error('glyphsUrl is not set');\n }\n\n if (!entry.requests[range]) {\n const promise = GlyphManager.loadGlyphRange(stack, range, this.url, this.requestManager);\n entry.requests[range] = promise;\n }\n\n const response = await entry.requests[range];\n for (const id in response) {\n if (!this._doesCharSupportLocalGlyph(+id)) {\n entry.glyphs[+id] = response[+id];\n }\n }\n entry.ranges[range] = true;\n return {stack, id, glyph: response[id] || null};\n }\n\n _doesCharSupportLocalGlyph(id: number): boolean {\n // The CJK Unified Ideographs blocks and Hangul Syllables blocks are\n // spread across many glyph PBFs and are typically accessed very\n // randomly. Preferring local rendering for these blocks reduces\n // wasteful bandwidth consumption. For visual consistency within CJKV\n // text, also include any other CJKV or siniform ideograph or hangul,\n // hiragana, or katakana character.\n return !!this.localIdeographFontFamily &&\n /\\p{Ideo}|\\p{sc=Hang}|\\p{sc=Hira}|\\p{sc=Kana}/u.test(String.fromCodePoint(id));\n }\n\n _tinySDF(entry: Entry, stack: string, id: number): StyleGlyph {\n const fontFamily = this.localIdeographFontFamily;\n if (!fontFamily) {\n return;\n }\n\n if (!this._doesCharSupportLocalGlyph(id)) {\n return;\n }\n\n // Client-generated glyphs are rendered at 2x texture scale,\n // because CJK glyphs are more detailed than others.\n const textureScale = 2;\n\n let tinySDF = entry.tinySDF;\n if (!tinySDF) {\n let fontWeight = '400';\n if (/bold/i.test(stack)) {\n fontWeight = '900';\n } else if (/medium/i.test(stack)) {\n fontWeight = '500';\n } else if (/light/i.test(stack)) {\n fontWeight = '200';\n }\n tinySDF = entry.tinySDF = new GlyphManager.TinySDF({\n fontSize: 24 * textureScale,\n buffer: 3 * textureScale,\n radius: 8 * textureScale,\n cutoff: 0.25,\n fontFamily,\n fontWeight\n });\n }\n\n const char = tinySDF.draw(String.fromCharCode(id));\n\n /**\n * TinySDF's \"top\" is the distance from the alphabetic baseline to the top of the glyph.\n * Server-generated fonts specify \"top\" relative to an origin above the em box (the origin\n * comes from FreeType, but I'm unclear on exactly how it's derived)\n * ref: https://github.com/mapbox/sdf-glyph-foundry\n *\n * Server fonts don't yet include baseline information, so we can't line up exactly with them\n * (and they don't line up with each other)\n * ref: https://github.com/mapbox/node-fontnik/pull/160\n *\n * To approximately align TinySDF glyphs with server-provided glyphs, we use this baseline adjustment\n * factor calibrated to be in between DIN Pro and Arial Unicode (but closer to Arial Unicode)\n */\n const topAdjustment = 27.5;\n\n const leftAdjustment = 0.5;\n\n return {\n id,\n bitmap: new AlphaImage({width: char.width || 30 * textureScale, height: char.height || 30 * textureScale}, char.data),\n metrics: {\n width: char.glyphWidth / textureScale || 24,\n height: char.glyphHeight / textureScale || 24,\n left: (char.glyphLeft / textureScale + leftAdjustment) || 0,\n top: char.glyphTop / textureScale - topAdjustment || -8,\n advance: char.glyphAdvance / textureScale || 24,\n isDoubleResolution: true\n }\n };\n }\n}\n","import {getArrayBuffer} from '../util/ajax';\nimport {ResourceType} from '../util/request_manager';\n\nimport {parseGlyphPbf} from './parse_glyph_pbf';\n\nimport type {StyleGlyph} from './style_glyph';\nimport type {RequestManager} from '../util/request_manager';\n\nexport async function loadGlyphRange(fontstack: string,\n range: number,\n urlTemplate: string,\n requestManager: RequestManager): Promise<{[_: number]: StyleGlyph | null}> {\n const begin = range * 256;\n const end = begin + 255;\n\n const request = requestManager.transformRequest(\n urlTemplate.replace('{fontstack}', fontstack).replace('{range}', `${begin}-${end}`),\n ResourceType.Glyphs\n );\n\n const response = await getArrayBuffer(request, new AbortController());\n if (!response || !response.data) {\n throw new Error(`Could not load glyph range. range: ${range}, ${begin}-${end}`);\n }\n const glyphs = {};\n\n for (const glyph of parseGlyphPbf(response.data)) {\n glyphs[glyph.id] = glyph;\n }\n\n return glyphs;\n}\n","import {interpolates, Color, latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {sphericalToCartesian} from '../util/util';\nimport {Evented} from '../util/evented';\nimport {\n validateStyle,\n validateLight,\n emitValidationErrors\n} from './validate_style';\n\nimport type {StylePropertySpecification, LightSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {EvaluationParameters} from './evaluation_parameters';\nimport type {StyleSetterOptions} from '../style/style';\nimport {Properties, Transitionable, Transitioning, PossiblyEvaluated, DataConstantProperty} from './properties';\n\nimport type {\n Property,\n PropertyValue,\n TransitionParameters\n} from './properties';\n\ntype LightPosition = {\n x: number;\n y: number;\n z: number;\n};\n\nclass LightPositionProperty implements Property<[number, number, number], LightPosition> {\n specification: StylePropertySpecification;\n\n constructor() {\n this.specification = styleSpec.light.position as StylePropertySpecification;\n }\n\n possiblyEvaluate(\n value: PropertyValue<[number, number, number], LightPosition>,\n parameters: EvaluationParameters\n ): LightPosition {\n return sphericalToCartesian(value.expression.evaluate(parameters));\n }\n\n interpolate(a: LightPosition, b: LightPosition, t: number): LightPosition {\n return {\n x: interpolates.number(a.x, b.x, t),\n y: interpolates.number(a.y, b.y, t),\n z: interpolates.number(a.z, b.z, t),\n };\n }\n}\n\ntype LightProps = {\n 'anchor': DataConstantProperty<'map' | 'viewport'>;\n 'position': LightPositionProperty;\n 'color': DataConstantProperty;\n 'intensity': DataConstantProperty;\n};\n\ntype LightPropsPossiblyEvaluated = {\n 'anchor': 'map' | 'viewport';\n 'position': LightPosition;\n 'color': Color;\n 'intensity': number;\n};\n\nconst TRANSITION_SUFFIX = '-transition';\n\nlet lightProperties: Properties;\n\n/*\n * Represents the light used to light extruded features.\n */\nexport class Light extends Evented {\n _transitionable: Transitionable;\n _transitioning: Transitioning;\n properties: PossiblyEvaluated;\n\n constructor(lightOptions?: LightSpecification) {\n super();\n lightProperties = lightProperties || new Properties({\n 'anchor': new DataConstantProperty(styleSpec.light.anchor as StylePropertySpecification),\n 'position': new LightPositionProperty(),\n 'color': new DataConstantProperty(styleSpec.light.color as StylePropertySpecification),\n 'intensity': new DataConstantProperty(styleSpec.light.intensity as StylePropertySpecification),\n });\n this._transitionable = new Transitionable(lightProperties);\n this.setLight(lightOptions);\n this._transitioning = this._transitionable.untransitioned();\n }\n\n getLight(): LightSpecification {\n return this._transitionable.serialize();\n }\n\n setLight(light?: LightSpecification, options: StyleSetterOptions = {}) {\n if (this._validate(validateLight, light, options)) {\n return;\n }\n\n for (const name in light) {\n const value = light[name];\n if (name.endsWith(TRANSITION_SUFFIX)) {\n this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length) as keyof LightProps, value);\n } else {\n this._transitionable.setValue(name as keyof LightProps, value);\n }\n }\n }\n\n updateTransitions(parameters: TransitionParameters) {\n this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);\n }\n\n hasTransition() {\n return this._transitioning.hasTransition();\n }\n\n recalculate(parameters: EvaluationParameters) {\n this.properties = this._transitioning.possiblyEvaluate(parameters);\n }\n\n _validate(validate: Function, value: unknown, options?: {\n validate?: boolean;\n }) {\n if (options && options.validate === false) {\n return false;\n }\n\n return emitValidationErrors(this, validate.call(validateStyle, {\n value,\n // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407\n style: {glyphs: true, sprite: true},\n styleSpec\n }));\n }\n}\n","import {DataConstantProperty, PossiblyEvaluated, Properties, Transitionable, Transitioning, TransitionParameters} from './properties';\nimport {Evented} from '../util/evented';\nimport {EvaluationParameters} from './evaluation_parameters';\nimport {emitValidationErrors, validateSky, validateStyle} from './validate_style';\nimport {extend} from '../util/util';\nimport {Color, latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\nimport {Mesh} from '../render/mesh';\nimport type {StylePropertySpecification, SkySpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {StyleSetterOptions} from './style';\n\ntype SkyProps = {\n 'sky-color': DataConstantProperty;\n 'horizon-color': DataConstantProperty;\n 'fog-color': DataConstantProperty;\n 'fog-ground-blend': DataConstantProperty;\n 'horizon-fog-blend': DataConstantProperty;\n 'sky-horizon-blend': DataConstantProperty;\n 'atmosphere-blend': DataConstantProperty;\n};\n\ntype SkyPropsPossiblyEvaluated = {\n 'sky-color': Color;\n 'horizon-color': Color;\n 'fog-color': Color;\n 'fog-ground-blend': number;\n 'horizon-fog-blend': number;\n 'sky-horizon-blend': number;\n 'atmosphere-blend': number;\n};\n\nconst properties: Properties = new Properties({\n 'sky-color': new DataConstantProperty(styleSpec.sky['sky-color'] as StylePropertySpecification),\n 'horizon-color': new DataConstantProperty(styleSpec.sky['horizon-color'] as StylePropertySpecification),\n 'fog-color': new DataConstantProperty(styleSpec.sky['fog-color'] as StylePropertySpecification),\n 'fog-ground-blend': new DataConstantProperty(styleSpec.sky['fog-ground-blend'] as StylePropertySpecification),\n 'horizon-fog-blend': new DataConstantProperty(styleSpec.sky['horizon-fog-blend'] as StylePropertySpecification),\n 'sky-horizon-blend': new DataConstantProperty(styleSpec.sky['sky-horizon-blend'] as StylePropertySpecification),\n 'atmosphere-blend': new DataConstantProperty(styleSpec.sky['atmosphere-blend'] as StylePropertySpecification)\n});\n\nconst TRANSITION_SUFFIX = '-transition';\n\nexport class Sky extends Evented {\n properties: PossiblyEvaluated;\n\n /**\n * This is used to cache the gl mesh for the sky, it should be initialized only once.\n */\n mesh: Mesh | undefined;\n _transitionable: Transitionable;\n _transitioning: Transitioning;\n\n constructor(sky?: SkySpecification) {\n super();\n this._transitionable = new Transitionable(properties);\n this.setSky(sky);\n this._transitioning = this._transitionable.untransitioned();\n this.recalculate(new EvaluationParameters(0));\n }\n\n setSky(sky?: SkySpecification, options: StyleSetterOptions = {}) {\n if (this._validate(validateSky, sky, options)) return;\n\n if (!sky) {\n sky = {\n 'sky-color': 'transparent',\n 'horizon-color': 'transparent',\n 'fog-color': 'transparent',\n 'fog-ground-blend': 1,\n 'atmosphere-blend': 0,\n };\n }\n\n for (const name in sky) {\n const value = sky[name];\n if (name.endsWith(TRANSITION_SUFFIX)) {\n this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length) as keyof SkyProps, value);\n } else {\n this._transitionable.setValue(name as keyof SkyProps, value);\n }\n }\n }\n\n getSky(): SkySpecification {\n return this._transitionable.serialize();\n }\n\n updateTransitions(parameters: TransitionParameters) {\n this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);\n }\n\n hasTransition() {\n return this._transitioning.hasTransition();\n }\n\n recalculate(parameters: EvaluationParameters) {\n this.properties = this._transitioning.possiblyEvaluate(parameters);\n }\n\n _validate(validate: Function, value: unknown, options: StyleSetterOptions = {}) {\n if (options?.validate === false) {\n return false;\n }\n return emitValidationErrors(this, validate.call(validateStyle, extend({\n value,\n // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407\n style: {glyphs: true, sprite: true},\n styleSpec\n })));\n }\n\n /**\n * Currently fog is a very simple implementation, and should only used\n * to create an atmosphere near the horizon.\n * But because the fog is drawn from the far-clipping-plane to\n * map-center, and because the fog does nothing know about the horizon,\n * this method does a fadeout in respect of pitch. So, when the horizon\n * gets out of view, which is at about pitch 70, this methods calculates\n * the corresponding opacity values. Below pitch 60 the fog is completely\n * invisible.\n */\n calculateFogBlendOpacity(pitch: number) {\n if (pitch < 60) return 0; // disable\n if (pitch < 70) return (pitch - 60) / 10; // fade in\n return 1;\n }\n}\n","import {warnOnce} from '../util/util';\n\nimport type {Context} from '../gl/context';\n\n/**\n * A dash entry\n */\ntype DashEntry = {\n y: number;\n height: number;\n width: number;\n}\n\n/**\n * @internal\n * A LineAtlas lets us reuse rendered dashed lines\n * by writing many of them to a texture and then fetching their positions\n * using {@link LineAtlas#getDash}.\n *\n * @param width - the width\n * @param height - the height\n */\nexport class LineAtlas {\n width: number;\n height: number;\n nextRow: number;\n bytes: number;\n data: Uint8Array;\n dashEntry: {[_: string]: DashEntry};\n dirty: boolean;\n texture: WebGLTexture;\n\n constructor(width: number, height: number) {\n this.width = width;\n this.height = height;\n this.nextRow = 0;\n\n this.data = new Uint8Array(this.width * this.height);\n\n this.dashEntry = {};\n }\n\n /**\n * Get or create a dash line pattern.\n *\n * @param dasharray - the key (represented by numbers) to get the dash texture\n * @param round - whether to add circle caps in between dash segments\n * @returns position of dash texture in {@link DashEntry}\n */\n getDash(dasharray: Array, round: boolean) {\n const key = dasharray.join(',') + String(round);\n\n if (!this.dashEntry[key]) {\n this.dashEntry[key] = this.addDash(dasharray, round);\n }\n return this.dashEntry[key];\n }\n\n getDashRanges(dasharray: Array, lineAtlasWidth: number, stretch: number) {\n // If dasharray has an odd length, both the first and last parts\n // are dashes and should be joined seamlessly.\n const oddDashArray = dasharray.length % 2 === 1;\n\n const ranges = [];\n\n let left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0;\n let right = dasharray[0] * stretch;\n let isDash = true;\n\n ranges.push({left, right, isDash, zeroLength: dasharray[0] === 0});\n\n let currentDashLength = dasharray[0];\n for (let i = 1; i < dasharray.length; i++) {\n isDash = !isDash;\n\n const dashLength = dasharray[i];\n left = currentDashLength * stretch;\n currentDashLength += dashLength;\n right = currentDashLength * stretch;\n\n ranges.push({left, right, isDash, zeroLength: dashLength === 0});\n }\n\n return ranges;\n }\n\n addRoundDash(ranges: any, stretch: number, n: number) {\n const halfStretch = stretch / 2;\n\n for (let y = -n; y <= n; y++) {\n const row = this.nextRow + n + y;\n const index = this.width * row;\n let currIndex = 0;\n let range = ranges[currIndex];\n\n for (let x = 0; x < this.width; x++) {\n if (x / range.right > 1) { range = ranges[++currIndex]; }\n\n const distLeft = Math.abs(x - range.left);\n const distRight = Math.abs(x - range.right);\n const minDist = Math.min(distLeft, distRight);\n let signedDistance;\n\n const distMiddle = y / n * (halfStretch + 1);\n if (range.isDash) {\n const distEdge = halfStretch - Math.abs(distMiddle);\n signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge);\n } else {\n signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle);\n }\n\n this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));\n }\n }\n }\n\n addRegularDash(ranges: any) {\n\n // Collapse any zero-length range\n // Collapse neighbouring same-type parts into a single part\n for (let i = ranges.length - 1; i >= 0; --i) {\n const part = ranges[i];\n const next = ranges[i + 1];\n if (part.zeroLength) {\n ranges.splice(i, 1);\n } else if (next && next.isDash === part.isDash) {\n next.left = part.left;\n ranges.splice(i, 1);\n }\n }\n\n // Combine the first and last parts if possible\n const first = ranges[0];\n const last = ranges[ranges.length - 1];\n if (first.isDash === last.isDash) {\n first.left = last.left - this.width;\n last.right = first.right + this.width;\n }\n\n const index = this.width * this.nextRow;\n let currIndex = 0;\n let range = ranges[currIndex];\n\n for (let x = 0; x < this.width; x++) {\n if (x / range.right > 1) {\n range = ranges[++currIndex];\n }\n\n const distLeft = Math.abs(x - range.left);\n const distRight = Math.abs(x - range.right);\n\n const minDist = Math.min(distLeft, distRight);\n const signedDistance = range.isDash ? minDist : -minDist;\n\n this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));\n }\n }\n\n addDash(dasharray: Array, round: boolean): DashEntry {\n const n = round ? 7 : 0;\n const height = 2 * n + 1;\n\n if (this.nextRow + height > this.height) {\n warnOnce('LineAtlas out of space');\n return null;\n }\n\n let length = 0;\n for (let i = 0; i < dasharray.length; i++) { length += dasharray[i]; }\n\n if (length !== 0) {\n const stretch = this.width / length;\n const ranges = this.getDashRanges(dasharray, this.width, stretch);\n\n if (round) {\n this.addRoundDash(ranges, stretch, n);\n } else {\n this.addRegularDash(ranges);\n }\n }\n\n const dashEntry = {\n y: (this.nextRow + n + 0.5) / this.height,\n height: 2 * n / this.height,\n width: length\n };\n\n this.nextRow += height;\n this.dirty = true;\n\n return dashEntry;\n }\n\n bind(context: Context) {\n const gl = context.gl;\n if (!this.texture) {\n this.texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this.width, this.height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this.data);\n\n } else {\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n if (this.dirty) {\n this.dirty = false;\n gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.width, this.height, gl.ALPHA, gl.UNSIGNED_BYTE, this.data);\n }\n }\n }\n}\n","/**\n * Invokes the wrapped function in a non-blocking way when trigger() is called.\n * Invocation requests are ignored until the function was actually invoked.\n */\nexport class ThrottledInvoker {\n _channel: MessageChannel;\n _triggered: boolean;\n _methodToThrottle: Function;\n\n constructor(methodToThrottle: Function) {\n this._methodToThrottle = methodToThrottle;\n this._triggered = false;\n if (typeof MessageChannel !== 'undefined') {\n this._channel = new MessageChannel();\n this._channel.port2.onmessage = () => {\n this._triggered = false;\n this._methodToThrottle();\n };\n }\n }\n\n trigger() {\n if (this._triggered) {\n return;\n }\n this._triggered = true;\n if (this._channel) {\n this._channel.port1.postMessage(true);\n } else {\n setTimeout(() => {\n this._triggered = false;\n this._methodToThrottle();\n }, 0);\n }\n }\n\n remove() {\n delete this._channel;\n this._methodToThrottle = () => {};\n }\n}\n","import {Subscription, isWorker, subscribe} from './util';\nimport {serialize, deserialize, Serialized} from './web_worker_transfer';\nimport {ThrottledInvoker} from './throttled_invoker';\n\nimport {\n MessageType,\n type ActorMessage,\n type RequestResponseMessageMap} from './actor_messages';\n\n/**\n * An interface to be sent to the actor in order for it to allow communication between the worker and the main thread\n */\nexport interface ActorTarget {\n addEventListener: typeof window.addEventListener;\n removeEventListener: typeof window.removeEventListener;\n postMessage: typeof window.postMessage;\n terminate?: () => void;\n}\n\n/**\n * This is used to define the parameters of the message that is sent to the worker and back\n */\ntype MessageData = {\n id: string;\n type: MessageType | '' | '';\n origin: string;\n data?: Serialized;\n targetMapId?: string | number | null;\n mustQueue?: boolean;\n error?: Serialized | null;\n sourceMapId: string | number | null;\n}\n\ntype ResolveReject = {\n resolve: (value?: RequestResponseMessageMap[MessageType][1]) => void;\n reject: (reason?: Error) => void;\n}\n\n/**\n * This interface allowing to substitute only the sendAsync method of the Actor class.\n */\nexport interface IActor {\n sendAsync(message: ActorMessage, abortController?: AbortController): Promise;\n}\n\nexport type MessageHandler = (mapId: string | number, params: RequestResponseMessageMap[T][0], abortController?: AbortController) => Promise\n\n/**\n * An implementation of the [Actor design pattern](https://en.wikipedia.org/wiki/Actor_model)\n * that maintains the relationship between asynchronous tasks and the objects\n * that spin them off - in this case, tasks like parsing parts of styles,\n * owned by the styles\n */\nexport class Actor implements IActor {\n target: ActorTarget;\n mapId: string | number | null;\n resolveRejects: { [x: string]: ResolveReject};\n name: string;\n tasks: { [x: string]: MessageData };\n taskQueue: Array;\n abortControllers: { [x: number | string]: AbortController };\n invoker: ThrottledInvoker;\n globalScope: ActorTarget;\n messageHandlers: { [x in MessageType]?: MessageHandler};\n subscription: Subscription;\n\n /**\n * @param target - The target\n * @param mapId - A unique identifier for the Map instance using this Actor.\n */\n constructor(target: ActorTarget, mapId?: string | number) {\n this.target = target;\n this.mapId = mapId;\n this.resolveRejects = {};\n this.tasks = {};\n this.taskQueue = [];\n this.abortControllers = {};\n this.messageHandlers = {};\n this.invoker = new ThrottledInvoker(() => this.process());\n this.subscription = subscribe(this.target, 'message', (message) => this.receive(message), false);\n this.globalScope = isWorker(self) ? target : window;\n }\n\n registerMessageHandler(type: T, handler: MessageHandler) {\n this.messageHandlers[type] = handler;\n }\n\n /**\n * Sends a message from a main-thread map to a Worker or from a Worker back to\n * a main-thread map instance.\n * @param message - the message to send\n * @param abortController - an optional AbortController to abort the request\n * @returns a promise that will be resolved with the response data\n */\n sendAsync(message: ActorMessage, abortController?: AbortController): Promise {\n return new Promise((resolve, reject) => {\n // We're using a string ID instead of numbers because they are being used as object keys\n // anyway, and thus stringified implicitly. We use random IDs because an actor may receive\n // message from multiple other actors which could run in different execution context. A\n // linearly increasing ID could produce collisions.\n const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10);\n this.resolveRejects[id] = {\n resolve,\n reject\n };\n if (abortController) {\n abortController.signal.addEventListener('abort', () => {\n delete this.resolveRejects[id];\n const cancelMessage: MessageData = {\n id,\n type: '',\n origin: location.origin,\n targetMapId: message.targetMapId,\n sourceMapId: this.mapId\n };\n this.target.postMessage(cancelMessage);\n // In case of abort the current behavior is to keep the promise pending.\n }, {once: true});\n }\n const buffers: Array = [];\n const messageToPost: MessageData = {\n ...message,\n id,\n sourceMapId: this.mapId,\n origin: location.origin,\n data: serialize(message.data, buffers)\n };\n this.target.postMessage(messageToPost, {transfer: buffers});\n });\n }\n\n receive(message: {data: MessageData}) {\n const data = message.data;\n const id = data.id;\n if (data.origin !== 'file://' && location.origin !== 'file://' && data.origin !== 'resource://android' && location.origin !== 'resource://android' && data.origin !== location.origin) {\n return;\n }\n if (data.targetMapId && this.mapId !== data.targetMapId) {\n return;\n }\n if (data.type === '') {\n // Remove the original request from the queue. This is only possible if it\n // hasn't been kicked off yet. The id will remain in the queue, but because\n // there is no associated task, it will be dropped once it's time to execute it.\n delete this.tasks[id];\n const abortController = this.abortControllers[id];\n delete this.abortControllers[id];\n if (abortController) {\n abortController.abort();\n }\n return;\n }\n if (isWorker(self) || data.mustQueue) {\n // In workers, store the tasks that we need to process before actually processing them. This\n // is necessary because we want to keep receiving messages, and in particular,\n // messages. Some tasks may take a while in the worker thread, so before\n // executing the next task in our queue, postMessage preempts this and \n // messages can be processed. We're using a MessageChannel object to get throttle the\n // process() flow to one at a time.\n this.tasks[id] = data;\n this.taskQueue.push(id);\n this.invoker.trigger();\n return;\n }\n // In the main thread, process messages immediately so that other work does not slip in\n // between getting partial data back from workers.\n this.processTask(id, data);\n }\n\n process() {\n if (this.taskQueue.length === 0) {\n return;\n }\n const id = this.taskQueue.shift();\n const task = this.tasks[id];\n delete this.tasks[id];\n // Schedule another process call if we know there's more to process _before_ invoking the\n // current task. This is necessary so that processing continues even if the current task\n // doesn't execute successfully.\n if (this.taskQueue.length > 0) {\n this.invoker.trigger();\n }\n if (!task) {\n // If the task ID doesn't have associated task data anymore, it was canceled.\n return;\n }\n\n this.processTask(id, task);\n }\n\n async processTask(id: string, task: MessageData) {\n if (task.type === '') {\n // The `completeTask` function in the counterpart actor has been called, and we are now\n // resolving or rejecting the promise in the originating actor, if there is one.\n const resolveReject = this.resolveRejects[id];\n delete this.resolveRejects[id];\n if (!resolveReject) {\n // If we get a response, but don't have a resolve or reject, the request was canceled.\n return;\n }\n if (task.error) {\n resolveReject.reject(deserialize(task.error) as Error);\n } else {\n resolveReject.resolve(deserialize(task.data));\n }\n return;\n }\n if (!this.messageHandlers[task.type]) {\n this.completeTask(id, new Error(`Could not find a registered handler for ${task.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(', ')}`));\n return;\n }\n const params = deserialize(task.data) as RequestResponseMessageMap[MessageType][0];\n const abortController = new AbortController();\n this.abortControllers[id] = abortController;\n try {\n const data = await this.messageHandlers[task.type](task.sourceMapId, params, abortController);\n this.completeTask(id, null, data);\n } catch (err) {\n this.completeTask(id, err);\n }\n }\n\n completeTask(id: string, err: Error, data?: RequestResponseMessageMap[MessageType][1]) {\n const buffers: Array = [];\n delete this.abortControllers[id];\n const responseMessage: MessageData = {\n id,\n type: '',\n sourceMapId: this.mapId,\n origin: location.origin,\n error: err ? serialize(err) : null,\n data: serialize(data, buffers)\n };\n this.target.postMessage(responseMessage, {transfer: buffers});\n }\n\n remove() {\n this.invoker.remove();\n this.subscription.unsubscribe();\n }\n}\n","import {workerFactory} from './web_worker';\nimport {browser} from './browser';\nimport {isSafari} from './util';\nimport {ActorTarget} from './actor';\n\nexport const PRELOAD_POOL_ID = 'maplibre_preloaded_worker_pool';\n\n/**\n * Constructs a worker pool.\n */\nexport class WorkerPool {\n static workerCount: number;\n\n active: {\n [_ in number | string]: boolean;\n };\n workers: Array;\n\n constructor() {\n this.active = {};\n }\n\n acquire(mapId: number | string): Array {\n if (!this.workers) {\n // Lazily look up the value of getWorkerCount so that\n // client code has had a chance to set it.\n this.workers = [];\n while (this.workers.length < WorkerPool.workerCount) {\n this.workers.push(workerFactory());\n }\n }\n\n this.active[mapId] = true;\n return this.workers.slice();\n }\n\n release(mapId: number | string) {\n delete this.active[mapId];\n if (this.numActive() === 0) {\n this.workers.forEach((w) => {\n w.terminate();\n });\n this.workers = null;\n }\n }\n\n isPreloaded(): boolean {\n return !!this.active[PRELOAD_POOL_ID];\n }\n\n numActive(): number {\n return Object.keys(this.active).length;\n }\n}\n\n// Based on results from A/B testing: https://github.com/maplibre/maplibre-gl-js/pull/2354\nconst availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2);\nWorkerPool.workerCount = isSafari(globalThis) ? Math.max(Math.min(availableLogicalProcessors, 3), 1) : 1;\n","import {AddProtocolAction, config} from './config';\nimport type {default as MaplibreWorker} from '../source/worker';\nimport type {WorkerSourceConstructor} from '../source/worker_source';\n\nexport interface WorkerGlobalScopeInterface {\n importScripts(...urls: Array): void;\n registerWorkerSource: (sourceName: string, sourceConstructor: WorkerSourceConstructor) => void;\n registerRTLTextPlugin: (_: any) => void;\n addProtocol: (customProtocol: string, loadFn: AddProtocolAction) => void;\n removeProtocol: (customProtocol: string) => void;\n worker: MaplibreWorker;\n}\n\nexport function workerFactory() {\n return new Worker(config.WORKER_URL);\n}\n","import {WorkerPool, PRELOAD_POOL_ID} from './worker_pool';\n\nlet globalWorkerPool;\n\n/**\n * Creates (if necessary) and returns the single, global WorkerPool instance\n * to be shared across each Map\n */\nexport function getGlobalWorkerPool() {\n if (!globalWorkerPool) {\n globalWorkerPool = new WorkerPool();\n }\n return globalWorkerPool;\n}\n\n/**\n * Initializes resources like WebWorkers that can be shared across maps to lower load\n * times in some situations. `setWorkerUrl()` and `setWorkerCount()`, if being\n * used, must be set before `prewarm()` is called to have an effect.\n *\n * By default, the lifecycle of these resources is managed automatically, and they are\n * lazily initialized when a Map is first created. By invoking `prewarm()`, these\n * resources will be created ahead of time, and will not be cleared when the last Map\n * is removed from the page. This allows them to be re-used by new Map instances that\n * are created later. They can be manually cleared by calling\n * `clearPrewarmedResources()`. This is only necessary if your web page remains\n * active but stops using maps altogether.\n *\n * This is primarily useful when using GL-JS maps in a single page app, wherein a user\n * would navigate between various views that can cause Map instances to constantly be\n * created and destroyed.\n *\n * @example\n * ```ts\n * prewarm()\n * ```\n */\nexport function prewarm() {\n const workerPool = getGlobalWorkerPool();\n workerPool.acquire(PRELOAD_POOL_ID);\n}\n\n/**\n * Clears up resources that have previously been created by `prewarm()`.\n * Note that this is typically not necessary. You should only call this function\n * if you expect the user of your app to not return to a Map view at any point\n * in your application.\n *\n * @example\n * ```ts\n * clearPrewarmedResources()\n * ```\n */\nexport function clearPrewarmedResources() {\n const pool = globalWorkerPool;\n if (pool) {\n // Remove the pool only if all maps that referenced the preloaded global worker pool have been removed.\n if (pool.isPreloaded() && pool.numActive() === 1) {\n pool.release(PRELOAD_POOL_ID);\n globalWorkerPool = null;\n } else {\n 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()');\n }\n }\n}\n","import {Actor, MessageHandler} from './actor';\nimport {getGlobalWorkerPool} from './global_worker_pool';\nimport {GLOBAL_DISPATCHER_ID, makeRequest} from './ajax';\n\nimport type {WorkerPool} from './worker_pool';\nimport type {WorkerSource} from '../source/worker_source'; /* eslint-disable-line */ // this is used for the docs' import\nimport type {RequestResponseMessageMap} from './actor_messages';\nimport {MessageType} from './actor_messages';\n\n/**\n * Responsible for sending messages from a {@link Source} to an associated\n * {@link WorkerSource}.\n */\nexport class Dispatcher {\n workerPool: WorkerPool;\n actors: Array;\n currentActor: number;\n id: string | number;\n\n constructor(workerPool: WorkerPool, mapId: string | number) {\n this.workerPool = workerPool;\n this.actors = [];\n this.currentActor = 0;\n this.id = mapId;\n const workers = this.workerPool.acquire(mapId);\n for (let i = 0; i < workers.length; i++) {\n const worker = workers[i];\n const actor = new Actor(worker, mapId);\n actor.name = `Worker ${i}`;\n this.actors.push(actor);\n }\n if (!this.actors.length) throw new Error('No actors found');\n }\n\n /**\n * Broadcast a message to all Workers.\n */\n broadcast(type: T, data: RequestResponseMessageMap[T][0]): Promise {\n const promises: Promise[] = [];\n for (const actor of this.actors) {\n promises.push(actor.sendAsync({type, data}));\n }\n return Promise.all(promises);\n }\n\n /**\n * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion.\n * @returns An actor object backed by a web worker for processing messages.\n */\n getActor(): Actor {\n this.currentActor = (this.currentActor + 1) % this.actors.length;\n return this.actors[this.currentActor];\n }\n\n remove(mapRemoved: boolean = true) {\n this.actors.forEach((actor) => { actor.remove(); });\n this.actors = [];\n if (mapRemoved) this.workerPool.release(this.id);\n }\n\n public registerMessageHandler(type: T, handler: MessageHandler) {\n for (const actor of this.actors) {\n actor.registerMessageHandler(type, handler);\n }\n }\n}\n\nlet globalDispatcher: Dispatcher;\n\nexport function getGlobalDispatcher(): Dispatcher {\n if (!globalDispatcher) {\n globalDispatcher = new Dispatcher(getGlobalWorkerPool(), GLOBAL_DISPATCHER_ID);\n globalDispatcher.registerMessageHandler(MessageType.getResource, (_mapId, params, abortController) => {\n return makeRequest(params, abortController);\n });\n }\n return globalDispatcher;\n}\n","import type {SourceCache} from './source_cache';\nimport type {StyleLayer} from '../style/style_layer';\nimport type {CollisionIndex} from '../symbol/collision_index';\nimport type {Transform} from '../geo/transform';\nimport type {RetainedQueryData} from '../symbol/placement';\nimport type {FilterSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {MapGeoJSONFeature} from '../util/vectortile_to_geojson';\nimport type Point from '@mapbox/point-geometry';\nimport {mat4} from 'gl-matrix';\n\n/**\n * Options to pass to query the map for the rendered features\n */\nexport type QueryRenderedFeaturesOptions = {\n /**\n * An array of [style layer IDs](https://maplibre.org/maplibre-style-spec/#layer-id) for the query to inspect.\n * Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.\n */\n layers?: Array;\n /**\n * A [filter](https://maplibre.org/maplibre-style-spec/layers/#filter) to limit query results.\n */\n filter?: FilterSpecification;\n /**\n * An array of string representing the available images\n */\n availableImages?: Array;\n /**\n * Whether to check if the [options.filter] conforms to the MapLibre Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.\n */\n validate?: boolean;\n};\n\n/**\n * The options object related to the {@link Map#querySourceFeatures} method\n */\nexport type QuerySourceFeatureOptions = {\n /**\n * The name of the source layer to query. *For vector tile sources, this parameter is required.* For GeoJSON sources, it is ignored.\n */\n sourceLayer?: string;\n /**\n * A [filter](https://maplibre.org/maplibre-style-spec/layers/#filter)\n * to limit query results.\n */\n filter?: FilterSpecification;\n /**\n * Whether to check if the [parameters.filter] conforms to the MapLibre Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.\n * @defaultValue true\n */\n validate?: boolean;\n}\n\n/*\n * Returns a matrix that can be used to convert from tile coordinates to viewport pixel coordinates.\n */\nfunction getPixelPosMatrix(transform, tileID) {\n const t = mat4.create();\n mat4.translate(t, t, [1, 1, 0]);\n mat4.scale(t, t, [transform.width * 0.5, transform.height * 0.5, 1]);\n return mat4.multiply(t, t, transform.calculatePosMatrix(tileID.toUnwrapped()));\n}\n\nfunction queryIncludes3DLayer(layers: Array, styleLayers: {[_: string]: StyleLayer}, sourceID: string) {\n if (layers) {\n for (const layerID of layers) {\n const layer = styleLayers[layerID];\n if (layer && layer.source === sourceID && layer.type === 'fill-extrusion') {\n return true;\n }\n }\n } else {\n for (const key in styleLayers) {\n const layer = styleLayers[key];\n if (layer.source === sourceID && layer.type === 'fill-extrusion') {\n return true;\n }\n }\n }\n return false;\n}\n\nexport function queryRenderedFeatures(\n sourceCache: SourceCache,\n styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: any},\n queryGeometry: Array,\n params: QueryRenderedFeaturesOptions,\n transform: Transform\n): { [key: string]: Array<{featureIndex: number; feature: MapGeoJSONFeature}> } {\n\n const has3DLayer = queryIncludes3DLayer(params && params.layers, styleLayers, sourceCache.id);\n const maxPitchScaleFactor = transform.maxPitchScaleFactor();\n const tilesIn = sourceCache.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer);\n\n tilesIn.sort(sortTilesIn);\n const renderedFeatureLayers = [];\n for (const tileIn of tilesIn) {\n renderedFeatureLayers.push({\n wrappedTileID: tileIn.tileID.wrapped().key,\n queryResults: tileIn.tile.queryRenderedFeatures(\n styleLayers,\n serializedLayers,\n sourceCache._state,\n tileIn.queryGeometry,\n tileIn.cameraQueryGeometry,\n tileIn.scale,\n params,\n transform,\n maxPitchScaleFactor,\n getPixelPosMatrix(sourceCache.transform, tileIn.tileID))\n });\n }\n\n const result = mergeRenderedFeatureLayers(renderedFeatureLayers);\n\n // Merge state from SourceCache into the results\n for (const layerID in result) {\n result[layerID].forEach((featureWrapper) => {\n const feature = featureWrapper.feature as MapGeoJSONFeature;\n const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id);\n feature.source = feature.layer.source;\n if (feature.layer['source-layer']) {\n feature.sourceLayer = feature.layer['source-layer'];\n }\n feature.state = state;\n });\n }\n return result;\n}\n\nexport function queryRenderedSymbols(styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: StyleLayer},\n sourceCaches: {[_: string]: SourceCache},\n queryGeometry: Array,\n params: QueryRenderedFeaturesOptions,\n collisionIndex: CollisionIndex,\n retainedQueryData: {\n [_: number]: RetainedQueryData;\n }) {\n const result = {};\n const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry);\n const bucketQueryData = [];\n for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) {\n bucketQueryData.push(retainedQueryData[bucketInstanceId]);\n }\n bucketQueryData.sort(sortTilesIn);\n\n for (const queryData of bucketQueryData) {\n const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(\n renderedSymbols[queryData.bucketInstanceId],\n serializedLayers,\n queryData.bucketIndex,\n queryData.sourceLayerIndex,\n params.filter,\n params.layers,\n params.availableImages,\n styleLayers);\n\n for (const layerID in bucketSymbols) {\n const resultFeatures = result[layerID] = result[layerID] || [];\n const layerSymbols = bucketSymbols[layerID];\n layerSymbols.sort((a, b) => {\n // Match topDownFeatureComparator from FeatureIndex, but using\n // most recent sorting of features from bucket.sortFeatures\n const featureSortOrder = queryData.featureSortOrder;\n if (featureSortOrder) {\n // queryRenderedSymbols documentation says we'll return features in\n // \"top-to-bottom\" rendering order (aka last-to-first).\n // Actually there can be multiple symbol instances per feature, so\n // we sort each feature based on the first matching symbol instance.\n const sortedA = featureSortOrder.indexOf(a.featureIndex);\n const sortedB = featureSortOrder.indexOf(b.featureIndex);\n return sortedB - sortedA;\n } else {\n // Bucket hasn't been re-sorted based on angle, so use the\n // reverse of the order the features appeared in the data.\n return b.featureIndex - a.featureIndex;\n }\n });\n for (const symbolFeature of layerSymbols) {\n resultFeatures.push(symbolFeature);\n }\n }\n }\n\n // Merge state from SourceCache into the results\n for (const layerName in result) {\n result[layerName].forEach((featureWrapper) => {\n const feature = featureWrapper.feature;\n const layer = styleLayers[layerName];\n const sourceCache = sourceCaches[layer.source];\n const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id);\n feature.source = feature.layer.source;\n if (feature.layer['source-layer']) {\n feature.sourceLayer = feature.layer['source-layer'];\n }\n feature.state = state;\n });\n }\n return result;\n}\n\nexport function querySourceFeatures(sourceCache: SourceCache, params: QuerySourceFeatureOptions) {\n const tiles = sourceCache.getRenderableIds().map((id) => {\n return sourceCache.getTileByID(id);\n });\n\n const result = [];\n\n const dataTiles = {};\n for (let i = 0; i < tiles.length; i++) {\n const tile = tiles[i];\n const dataID = tile.tileID.canonical.key;\n if (!dataTiles[dataID]) {\n dataTiles[dataID] = true;\n tile.querySourceFeatures(result, params);\n }\n }\n\n return result;\n}\n\nfunction sortTilesIn(a, b) {\n const idA = a.tileID;\n const idB = b.tileID;\n return (idA.overscaledZ - idB.overscaledZ) || (idA.canonical.y - idB.canonical.y) || (idA.wrap - idB.wrap) || (idA.canonical.x - idB.canonical.x);\n}\n\nfunction mergeRenderedFeatureLayers(tiles) {\n // Merge results from all tiles, but if two tiles share the same\n // wrapped ID, don't duplicate features between the two tiles\n const result = {};\n const wrappedIDLayerMap = {};\n for (const tile of tiles) {\n const queryResults = tile.queryResults;\n const wrappedID = tile.wrappedTileID;\n const wrappedIDLayers = wrappedIDLayerMap[wrappedID] = wrappedIDLayerMap[wrappedID] || {};\n for (const layerID in queryResults) {\n const tileFeatures = queryResults[layerID];\n const wrappedIDFeatures = wrappedIDLayers[layerID] = wrappedIDLayers[layerID] || {};\n const resultFeatures = result[layerID] = result[layerID] || [];\n for (const tileFeature of tileFeatures) {\n if (!wrappedIDFeatures[tileFeature.featureIndex]) {\n wrappedIDFeatures[tileFeature.featureIndex] = true;\n resultFeatures.push(tileFeature);\n }\n }\n }\n }\n return result;\n}\n","import {pick, extend, TileJSON} from '../util/util';\nimport {getJSON} from '../util/ajax';\nimport {ResourceType} from '../util/request_manager';\nimport {browser} from '../util/browser';\n\nimport type {RequestManager} from '../util/request_manager';\nimport type {RasterDEMSourceSpecification, RasterSourceSpecification, VectorSourceSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport type LoadTileJsonResponse = {\n tiles: Array;\n minzoom: number;\n maxzoom: number;\n attribution: string;\n bounds: RasterSourceSpecification['bounds'];\n scheme: RasterSourceSpecification['scheme'];\n tileSize: number;\n encoding: RasterDEMSourceSpecification['encoding'];\n vectorLayerIds?: Array;\n}\n\nexport async function loadTileJson(\n options: RasterSourceSpecification | RasterDEMSourceSpecification | VectorSourceSpecification,\n requestManager: RequestManager,\n abortController: AbortController,\n): Promise {\n let tileJSON: TileJSON | typeof options = options;\n if (options.url) {\n const response = await getJSON(requestManager.transformRequest(options.url, ResourceType.Source), abortController);\n tileJSON = response.data;\n } else {\n await browser.frameAsync(abortController);\n }\n if (!tileJSON) {\n return null;\n }\n const result = pick(\n // explicit source options take precedence over TileJSON\n extend(tileJSON, options),\n ['tiles', 'minzoom', 'maxzoom', 'attribution', 'bounds', 'scheme', 'tileSize', 'encoding']\n ) as LoadTileJsonResponse;\n\n if ('vector_layers' in tileJSON && tileJSON.vector_layers) {\n result.vectorLayerIds = tileJSON.vector_layers.map((layer) => { return layer.id; });\n }\n\n return result;\n}\n","import {wrap} from '../util/util';\n\n/*\n* Approximate radius of the earth in meters.\n* Uses the WGS-84 approximation. The radius at the equator is ~6378137 and at the poles is ~6356752. https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84\n* 6371008.8 is one published \"average radius\" see https://en.wikipedia.org/wiki/Earth_radius#Mean_radius, or ftp://athena.fsv.cvut.cz/ZFG/grs80-Moritz.pdf p.4\n*/\nexport const earthRadius = 6371008.8;\n\n/**\n * A {@link LngLat} object, an array of two numbers representing longitude and latitude,\n * or an object with `lng` and `lat` or `lon` and `lat` properties.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let v1 = new LngLat(-122.420679, 37.772537);\n * let v2 = [-122.420679, 37.772537];\n * let v3 = {lon: -122.420679, lat: 37.772537};\n * ```\n */\nexport type LngLatLike = LngLat | {\n lng: number;\n lat: number;\n} | {\n lon: number;\n lat: number;\n} | [number, number];\n\n/**\n * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees.\n * These coordinates are based on the [WGS84 (EPSG:4326) standard](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84).\n *\n * MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match the\n * [GeoJSON specification](https://tools.ietf.org/html/rfc7946).\n *\n * Note that any MapLibre GL JS method that accepts a `LngLat` object as an argument or option\n * can also accept an `Array` of two numbers and will perform an implicit conversion.\n * This flexible type is documented as {@link LngLatLike}.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let ll = new LngLat(-123.9749, 40.7736);\n * ll.lng; // = -123.9749\n * ```\n * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/)\n * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/)\n * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/)\n */\nexport class LngLat {\n lng: number;\n lat: number;\n\n /**\n * @param lng - Longitude, measured in degrees.\n * @param lat - Latitude, measured in degrees.\n */\n constructor(lng: number, lat: number) {\n if (isNaN(lng) || isNaN(lat)) {\n throw new Error(`Invalid LngLat object: (${lng}, ${lat})`);\n }\n this.lng = +lng;\n this.lat = +lat;\n if (this.lat > 90 || this.lat < -90) {\n throw new Error('Invalid LngLat latitude value: must be between -90 and 90');\n }\n }\n\n /**\n * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180).\n *\n * @returns The wrapped `LngLat` object.\n * @example\n * ```ts\n * let ll = new LngLat(286.0251, 40.7736);\n * let wrapped = ll.wrap();\n * wrapped.lng; // = -73.9749\n * ```\n */\n wrap() {\n return new LngLat(wrap(this.lng, -180, 180), this.lat);\n }\n\n /**\n * Returns the coordinates represented as an array of two numbers.\n *\n * @returns The coordinates represented as an array of longitude and latitude.\n * @example\n * ```ts\n * let ll = new LngLat(-73.9749, 40.7736);\n * ll.toArray(); // = [-73.9749, 40.7736]\n * ```\n */\n toArray(): [number, number] {\n return [this.lng, this.lat];\n }\n\n /**\n * Returns the coordinates represent as a string.\n *\n * @returns The coordinates represented as a string of the format `'LngLat(lng, lat)'`.\n * @example\n * ```ts\n * let ll = new LngLat(-73.9749, 40.7736);\n * ll.toString(); // = \"LngLat(-73.9749, 40.7736)\"\n * ```\n */\n toString(): string {\n return `LngLat(${this.lng}, ${this.lat})`;\n }\n\n /**\n * Returns the approximate distance between a pair of coordinates in meters\n * Uses the Haversine Formula (from R.W. Sinnott, \"Virtues of the Haversine\", Sky and Telescope, vol. 68, no. 2, 1984, p. 159)\n *\n * @param lngLat - coordinates to compute the distance to\n * @returns Distance in meters between the two coordinates.\n * @example\n * ```ts\n * let new_york = new LngLat(-74.0060, 40.7128);\n * let los_angeles = new LngLat(-118.2437, 34.0522);\n * new_york.distanceTo(los_angeles); // = 3935751.690893987, \"true distance\" using a non-spherical approximation is ~3966km\n * ```\n */\n distanceTo(lngLat: LngLat): number {\n const rad = Math.PI / 180;\n const lat1 = this.lat * rad;\n const lat2 = lngLat.lat * rad;\n const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad);\n\n const maxMeters = earthRadius * Math.acos(Math.min(a, 1));\n return maxMeters;\n }\n\n /**\n * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties\n * to a `LngLat` object.\n *\n * If a `LngLat` object is passed in, the function returns it unchanged.\n *\n * @param input - An array of two numbers or object to convert, or a `LngLat` object to return.\n * @returns A new `LngLat` object, if a conversion occurred, or the original `LngLat` object.\n * @example\n * ```ts\n * let arr = [-73.9749, 40.7736];\n * let ll = LngLat.convert(arr);\n * ll; // = LngLat {lng: -73.9749, lat: 40.7736}\n * ```\n */\n static convert(input: LngLatLike): LngLat {\n if (input instanceof LngLat) {\n return input;\n }\n if (Array.isArray(input) && (input.length === 2 || input.length === 3)) {\n return new LngLat(Number(input[0]), Number(input[1]));\n }\n if (!Array.isArray(input) && typeof input === 'object' && input !== null) {\n return new LngLat(\n // flow can't refine this to have one of lng or lat, so we have to cast to any\n Number('lng' in input ? (input as any).lng : (input as any).lon),\n Number(input.lat)\n );\n }\n throw new Error('`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]');\n }\n}\n","import {LngLat} from './lng_lat';\nimport type {LngLatLike} from './lng_lat';\n\n/**\n * A {@link LngLatBounds} object, an array of {@link LngLatLike} objects in [sw, ne] order,\n * or an array of numbers in [west, south, east, north] order.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let v1 = new LngLatBounds(\n * new LngLat(-73.9876, 40.7661),\n * new LngLat(-73.9397, 40.8002)\n * );\n * let v2 = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002])\n * let v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]];\n * ```\n */\nexport type LngLatBoundsLike = LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number];\n\n/**\n * A `LngLatBounds` object represents a geographical bounding box,\n * defined by its southwest and northeast points in longitude and latitude.\n *\n * If no arguments are provided to the constructor, a `null` bounding box is created.\n *\n * Note that any Mapbox GL method that accepts a `LngLatBounds` object as an argument or option\n * can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion.\n * This flexible type is documented as {@link LngLatBoundsLike}.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let sw = new LngLat(-73.9876, 40.7661);\n * let ne = new LngLat(-73.9397, 40.8002);\n * let llb = new LngLatBounds(sw, ne);\n * ```\n */\nexport class LngLatBounds {\n _ne: LngLat;\n _sw: LngLat;\n\n /**\n * @param sw - The southwest corner of the bounding box.\n * OR array of 4 numbers in the order of west, south, east, north\n * OR array of 2 LngLatLike: [sw,ne]\n * @param ne - The northeast corner of the bounding box.\n * @example\n * ```ts\n * let sw = new LngLat(-73.9876, 40.7661);\n * let ne = new LngLat(-73.9397, 40.8002);\n * let llb = new LngLatBounds(sw, ne);\n * ```\n * OR\n * ```ts\n * let llb = new LngLatBounds([-73.9876, 40.7661, -73.9397, 40.8002]);\n * ```\n * OR\n * ```ts\n * let llb = new LngLatBounds([sw, ne]);\n * ```\n */\n constructor(sw?: LngLatLike | [number, number, number, number] | [LngLatLike, LngLatLike], ne?: LngLatLike) {\n if (!sw) {\n // noop\n } else if (ne) {\n this.setSouthWest(sw).setNorthEast(ne);\n } else if (Array.isArray(sw)) {\n if (sw.length === 4) {\n // 4 element array: west, south, east, north\n this.setSouthWest([sw[0], sw[1]]).setNorthEast([sw[2], sw[3]]);\n } else {\n this.setSouthWest(sw[0] as LngLatLike).setNorthEast(sw[1] as LngLatLike);\n }\n }\n }\n\n /**\n * Set the northeast corner of the bounding box\n *\n * @param ne - a {@link LngLatLike} object describing the northeast corner of the bounding box.\n */\n setNorthEast(ne: LngLatLike): this {\n this._ne = ne instanceof LngLat ? new LngLat(ne.lng, ne.lat) : LngLat.convert(ne);\n return this;\n }\n\n /**\n * Set the southwest corner of the bounding box\n *\n * @param sw - a {@link LngLatLike} object describing the southwest corner of the bounding box.\n */\n setSouthWest(sw: LngLatLike): this {\n this._sw = sw instanceof LngLat ? new LngLat(sw.lng, sw.lat) : LngLat.convert(sw);\n return this;\n }\n\n /**\n * Extend the bounds to include a given LngLatLike or LngLatBoundsLike.\n *\n * @param obj - object to extend to\n */\n extend(obj: LngLatLike | LngLatBoundsLike): this {\n const sw = this._sw,\n ne = this._ne;\n let sw2, ne2;\n\n if (obj instanceof LngLat) {\n sw2 = obj;\n ne2 = obj;\n\n } else if (obj instanceof LngLatBounds) {\n sw2 = obj._sw;\n ne2 = obj._ne;\n\n if (!sw2 || !ne2) return this;\n\n } else {\n if (Array.isArray(obj)) {\n if (obj.length === 4 || (obj as any[]).every(Array.isArray)) {\n const lngLatBoundsObj = (obj as any as LngLatBoundsLike);\n return this.extend(LngLatBounds.convert(lngLatBoundsObj));\n } else {\n const lngLatObj = (obj as any as LngLatLike);\n return this.extend(LngLat.convert(lngLatObj));\n }\n\n } else if (obj && ('lng' in obj || 'lon' in obj) && 'lat' in obj) {\n return this.extend(LngLat.convert(obj));\n }\n\n return this;\n }\n\n if (!sw && !ne) {\n this._sw = new LngLat(sw2.lng, sw2.lat);\n this._ne = new LngLat(ne2.lng, ne2.lat);\n\n } else {\n sw.lng = Math.min(sw2.lng, sw.lng);\n sw.lat = Math.min(sw2.lat, sw.lat);\n ne.lng = Math.max(ne2.lng, ne.lng);\n ne.lat = Math.max(ne2.lat, ne.lat);\n }\n\n return this;\n }\n\n /**\n * Returns the geographical coordinate equidistant from the bounding box's corners.\n *\n * @returns The bounding box's center.\n * @example\n * ```ts\n * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315}\n * ```\n */\n getCenter(): LngLat {\n return new LngLat((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2);\n }\n\n /**\n * Returns the southwest corner of the bounding box.\n *\n * @returns The southwest corner of the bounding box.\n */\n getSouthWest(): LngLat { return this._sw; }\n\n /**\n * Returns the northeast corner of the bounding box.\n *\n * @returns The northeast corner of the bounding box.\n */\n getNorthEast(): LngLat { return this._ne; }\n\n /**\n * Returns the northwest corner of the bounding box.\n *\n * @returns The northwest corner of the bounding box.\n */\n getNorthWest(): LngLat { return new LngLat(this.getWest(), this.getNorth()); }\n\n /**\n * Returns the southeast corner of the bounding box.\n *\n * @returns The southeast corner of the bounding box.\n */\n getSouthEast(): LngLat { return new LngLat(this.getEast(), this.getSouth()); }\n\n /**\n * Returns the west edge of the bounding box.\n *\n * @returns The west edge of the bounding box.\n */\n getWest(): number { return this._sw.lng; }\n\n /**\n * Returns the south edge of the bounding box.\n *\n * @returns The south edge of the bounding box.\n */\n getSouth(): number { return this._sw.lat; }\n\n /**\n * Returns the east edge of the bounding box.\n *\n * @returns The east edge of the bounding box.\n */\n getEast(): number { return this._ne.lng; }\n\n /**\n * Returns the north edge of the bounding box.\n *\n * @returns The north edge of the bounding box.\n */\n getNorth(): number { return this._ne.lat; }\n\n /**\n * Returns the bounding box represented as an array.\n *\n * @returns The bounding box represented as an array, consisting of the\n * southwest and northeast coordinates of the bounding represented as arrays of numbers.\n * @example\n * ```ts\n * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]]\n * ```\n */\n toArray() {\n return [this._sw.toArray(), this._ne.toArray()];\n }\n\n /**\n * Return the bounding box represented as a string.\n *\n * @returns The bounding box represents as a string of the format\n * `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`.\n * @example\n * ```ts\n * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.toString(); // = \"LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))\"\n * ```\n */\n toString() {\n return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`;\n }\n\n /**\n * Check if the bounding box is an empty/`null`-type box.\n *\n * @returns True if bounds have been defined, otherwise false.\n */\n isEmpty() {\n return !(this._sw && this._ne);\n }\n\n /**\n * Check if the point is within the bounding box.\n *\n * @param lnglat - geographic point to check against.\n * @returns `true` if the point is within the bounding box.\n * @example\n * ```ts\n * let llb = new LngLatBounds(\n * new LngLat(-73.9876, 40.7661),\n * new LngLat(-73.9397, 40.8002)\n * );\n *\n * let ll = new LngLat(-73.9567, 40.7789);\n *\n * console.log(llb.contains(ll)); // = true\n * ```\n */\n contains(lnglat: LngLatLike) {\n const {lng, lat} = LngLat.convert(lnglat);\n\n const containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat;\n let containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng;\n if (this._sw.lng > this._ne.lng) { // wrapped coordinates\n containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng;\n }\n\n return containsLatitude && containsLongitude;\n }\n\n /**\n * Converts an array to a `LngLatBounds` object.\n *\n * If a `LngLatBounds` object is passed in, the function returns it unchanged.\n *\n * Internally, the function calls `LngLat#convert` to convert arrays to `LngLat` values.\n *\n * @param input - An array of two coordinates to convert, or a `LngLatBounds` object to return.\n * @returns A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object.\n * @example\n * ```ts\n * let arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];\n * let llb = LngLatBounds.convert(arr); // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}}\n * ```\n */\n static convert(input: LngLatBoundsLike | null): LngLatBounds {\n if (input instanceof LngLatBounds) return input;\n if (!input) return input as null;\n return new LngLatBounds(input);\n }\n\n /**\n * Returns a `LngLatBounds` from the coordinates extended by a given `radius`. The returned `LngLatBounds` completely contains the `radius`.\n *\n * @param center - center coordinates of the new bounds.\n * @param radius - Distance in meters from the coordinates to extend the bounds.\n * @returns A new `LngLatBounds` object representing the coordinates extended by the `radius`.\n * @example\n * ```ts\n * let center = new LngLat(-73.9749, 40.7736);\n * LngLatBounds.fromLngLat(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]]\n * ```\n */\n static fromLngLat(center: LngLat, radius:number = 0): LngLatBounds {\n const earthCircumferenceInMetersAtEquator = 40075017;\n const latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator,\n lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * center.lat);\n\n return new LngLatBounds(new LngLat(center.lng - lngAccuracy, center.lat - latAccuracy),\n new LngLat(center.lng + lngAccuracy, center.lat + latAccuracy));\n }\n\n /**\n * Adjusts the given bounds to handle the case where the bounds cross the 180th meridian (antimeridian).\n *\n * @returns The adjusted LngLatBounds\n * @example\n * ```ts\n * let bounds = new LngLatBounds([175.813127, -20.157768], [-178. 340903, -15.449124]);\n * let adjustedBounds = bounds.adjustAntiMeridian();\n * // adjustedBounds will be: [[175.813127, -20.157768], [181.659097, -15.449124]]\n * ```\n */\n adjustAntiMeridian(): LngLatBounds {\n const sw = new LngLat(this._sw.lng, this._sw.lat);\n const ne = new LngLat(this._ne.lng, this._ne.lat);\n\n if (sw.lng > ne.lng) {\n return new LngLatBounds(\n sw,\n new LngLat(ne.lng + 360, ne.lat)\n );\n }\n\n return new LngLatBounds(sw, ne);\n }\n\n}\n","import {LngLat, earthRadius} from '../geo/lng_lat';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport {IMercatorCoordinate} from '@maplibre/maplibre-gl-style-spec';\n\n/*\n * The average circumference of the world in meters.\n */\nconst earthCircumference = 2 * Math.PI * earthRadius; // meters\n\n/*\n * The circumference at a line of latitude in meters.\n */\nfunction circumferenceAtLatitude(latitude: number) {\n return earthCircumference * Math.cos(latitude * Math.PI / 180);\n}\n\nexport function mercatorXfromLng(lng: number) {\n return (180 + lng) / 360;\n}\n\nexport function mercatorYfromLat(lat: number) {\n return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;\n}\n\nexport function mercatorZfromAltitude(altitude: number, lat: number) {\n return altitude / circumferenceAtLatitude(lat);\n}\n\nexport function lngFromMercatorX(x: number) {\n return x * 360 - 180;\n}\n\nexport function latFromMercatorY(y: number) {\n const y2 = 180 - y * 360;\n return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90;\n}\n\nexport function altitudeFromMercatorZ(z: number, y: number) {\n return z * circumferenceAtLatitude(latFromMercatorY(y));\n}\n\n/**\n * Determine the Mercator scale factor for a given latitude, see\n * https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor\n *\n * At the equator the scale factor will be 1, which increases at higher latitudes.\n *\n * @param lat - Latitude\n * @returns scale factor\n */\nexport function mercatorScale(lat: number) {\n return 1 / Math.cos(lat * Math.PI / 180);\n}\n\n/**\n * A `MercatorCoordinate` object represents a projected three dimensional position.\n *\n * `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units:\n *\n * - the size of 1 unit is the width of the projected world instead of the \"mercator meter\"\n * - the origin of the coordinate space is at the north-west corner instead of the middle\n *\n * For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and\n * `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with\n * [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think\n * of the coordinate space as the `0/0/0` tile with an extent of `1`.\n *\n * The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let nullIsland = new MercatorCoordinate(0.5, 0.5, 0);\n * ```\n * @see [Add a custom style layer](https://maplibre.org/maplibre-gl-js/docs/examples/custom-style-layer/)\n */\nexport class MercatorCoordinate implements IMercatorCoordinate {\n x: number;\n y: number;\n z: number;\n\n /**\n * @param x - The x component of the position.\n * @param y - The y component of the position.\n * @param z - The z component of the position.\n */\n constructor(x: number, y: number, z: number = 0) {\n this.x = +x;\n this.y = +y;\n this.z = +z;\n }\n\n /**\n * Project a `LngLat` to a `MercatorCoordinate`.\n *\n * @param lngLatLike - The location to project.\n * @param altitude - The altitude in meters of the position.\n * @returns The projected mercator coordinate.\n * @example\n * ```ts\n * let coord = MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0);\n * coord; // MercatorCoordinate(0.5, 0.5, 0)\n * ```\n */\n static fromLngLat(lngLatLike: LngLatLike, altitude: number = 0): MercatorCoordinate {\n const lngLat = LngLat.convert(lngLatLike);\n\n return new MercatorCoordinate(\n mercatorXfromLng(lngLat.lng),\n mercatorYfromLat(lngLat.lat),\n mercatorZfromAltitude(altitude, lngLat.lat));\n }\n\n /**\n * Returns the `LngLat` for the coordinate.\n *\n * @returns The `LngLat` object.\n * @example\n * ```ts\n * let coord = new MercatorCoordinate(0.5, 0.5, 0);\n * let lngLat = coord.toLngLat(); // LngLat(0, 0)\n * ```\n */\n toLngLat() {\n return new LngLat(\n lngFromMercatorX(this.x),\n latFromMercatorY(this.y));\n }\n\n /**\n * Returns the altitude in meters of the coordinate.\n *\n * @returns The altitude in meters.\n * @example\n * ```ts\n * let coord = new MercatorCoordinate(0, 0, 0.02);\n * coord.toAltitude(); // 6914.281956295339\n * ```\n */\n toAltitude(): number {\n return altitudeFromMercatorZ(this.z, this.y);\n }\n\n /**\n * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude.\n *\n * For coordinates in real world units using meters, this naturally provides the scale\n * to transform into `MercatorCoordinate`s.\n *\n * @returns Distance of 1 meter in `MercatorCoordinate` units.\n */\n meterInMercatorCoordinateUnits(): number {\n // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude\n return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y));\n }\n}\n","import {LngLatBounds, LngLatBoundsLike} from '../geo/lng_lat_bounds';\nimport {mercatorXfromLng, mercatorYfromLat} from '../geo/mercator_coordinate';\n\nimport type {CanonicalTileID} from './tile_id';\n\nexport class TileBounds {\n bounds: LngLatBounds;\n minzoom: number;\n maxzoom: number;\n\n constructor(bounds: [number, number, number, number], minzoom?: number | null, maxzoom?: number | null) {\n this.bounds = LngLatBounds.convert(this.validateBounds(bounds));\n this.minzoom = minzoom || 0;\n this.maxzoom = maxzoom || 24;\n }\n\n validateBounds(bounds: [number, number, number, number]): LngLatBoundsLike {\n // make sure the bounds property contains valid longitude and latitudes\n if (!Array.isArray(bounds) || bounds.length !== 4) return [-180, -90, 180, 90];\n return [Math.max(-180, bounds[0]), Math.max(-90, bounds[1]), Math.min(180, bounds[2]), Math.min(90, bounds[3])];\n }\n\n contains(tileID: CanonicalTileID) {\n const worldSize = Math.pow(2, tileID.z);\n const level = {\n minX: Math.floor(mercatorXfromLng(this.bounds.getWest()) * worldSize),\n minY: Math.floor(mercatorYfromLat(this.bounds.getNorth()) * worldSize),\n maxX: Math.ceil(mercatorXfromLng(this.bounds.getEast()) * worldSize),\n maxY: Math.ceil(mercatorYfromLat(this.bounds.getSouth()) * worldSize)\n };\n const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;\n return hit;\n }\n}\n","import {Event, ErrorEvent, Evented} from '../util/evented';\n\nimport {extend, pick} from '../util/util';\nimport {loadTileJson} from './load_tilejson';\nimport {TileBounds} from './tile_bounds';\nimport {ResourceType} from '../util/request_manager';\n\nimport type {Source} from './source';\nimport type {OverscaledTileID} from './tile_id';\nimport type {Map} from '../ui/map';\nimport type {Dispatcher} from '../util/dispatcher';\nimport type {Tile} from './tile';\nimport type {VectorSourceSpecification, PromoteIdSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {WorkerTileResult} from './worker_source';\nimport {MessageType} from '../util/actor_messages';\n\nexport type VectorTileSourceOptions = VectorSourceSpecification & {\n collectResourceTiming?: boolean;\n tileSize?: number;\n}\n\n/**\n * A source containing vector tiles in [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/).\n * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.)\n *\n * @group Sources\n *\n * @example\n * ```ts\n * map.addSource('some id', {\n * type: 'vector',\n * url: 'https://demotiles.maplibre.org/tiles/tiles.json'\n * });\n * ```\n *\n * @example\n * ```ts\n * map.addSource('some id', {\n * type: 'vector',\n * tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'],\n * minzoom: 6,\n * maxzoom: 14\n * });\n * ```\n *\n * @example\n * ```ts\n * map.getSource('some id').setUrl(\"https://demotiles.maplibre.org/tiles/tiles.json\");\n * ```\n *\n * @example\n * ```ts\n * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']);\n * ```\n * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/)\n */\nexport class VectorTileSource extends Evented implements Source {\n type: 'vector';\n id: string;\n minzoom: number;\n maxzoom: number;\n url: string;\n scheme: string;\n tileSize: number;\n promoteId: PromoteIdSpecification;\n\n _options: VectorSourceSpecification;\n _collectResourceTiming: boolean;\n dispatcher: Dispatcher;\n map: Map;\n bounds: [number, number, number, number];\n tiles: Array;\n tileBounds: TileBounds;\n reparseOverscaled: boolean;\n isTileClipped: boolean;\n _tileJSONRequest: AbortController;\n _loaded: boolean;\n\n constructor(id: string, options: VectorTileSourceOptions, dispatcher: Dispatcher, eventedParent: Evented) {\n super();\n this.id = id;\n this.dispatcher = dispatcher;\n\n this.type = 'vector';\n this.minzoom = 0;\n this.maxzoom = 22;\n this.scheme = 'xyz';\n this.tileSize = 512;\n this.reparseOverscaled = true;\n this.isTileClipped = true;\n this._loaded = false;\n\n extend(this, pick(options, ['url', 'scheme', 'tileSize', 'promoteId']));\n this._options = extend({type: 'vector'}, options);\n\n this._collectResourceTiming = options.collectResourceTiming;\n\n if (this.tileSize !== 512) {\n throw new Error('vector tile sources must have a tileSize of 512');\n }\n\n this.setEventedParent(eventedParent);\n }\n\n async load() {\n this._loaded = false;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._tileJSONRequest = new AbortController();\n try {\n const tileJSON = await loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest);\n this._tileJSONRequest = null;\n this._loaded = true;\n this.map.style.sourceCaches[this.id].clearTiles();\n if (tileJSON) {\n extend(this, tileJSON);\n if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);\n\n // `content` is included here to prevent a race condition where `Style#_updateSources` is called\n // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives\n // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'}));\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'content'}));\n }\n } catch (err) {\n this._tileJSONRequest = null;\n this.fire(new ErrorEvent(err));\n }\n }\n\n loaded(): boolean {\n return this._loaded;\n }\n\n hasTile(tileID: OverscaledTileID) {\n return !this.tileBounds || this.tileBounds.contains(tileID.canonical);\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n }\n\n setSourceProperty(callback: Function) {\n if (this._tileJSONRequest) {\n this._tileJSONRequest.abort();\n }\n\n callback();\n\n this.load();\n }\n\n /**\n * Sets the source `tiles` property and re-renders the map.\n *\n * @param tiles - An array of one or more tile source URLs, as in the TileJSON spec.\n */\n setTiles(tiles: Array): this {\n this.setSourceProperty(() => {\n this._options.tiles = tiles;\n });\n\n return this;\n }\n\n /**\n * Sets the source `url` property and re-renders the map.\n *\n * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`.\n */\n setUrl(url: string): this {\n this.setSourceProperty(() => {\n this.url = url;\n this._options.url = url;\n });\n\n return this;\n }\n\n onRemove() {\n if (this._tileJSONRequest) {\n this._tileJSONRequest.abort();\n this._tileJSONRequest = null;\n }\n }\n\n serialize(): VectorSourceSpecification {\n return extend({}, this._options);\n }\n\n async loadTile(tile: Tile): Promise {\n const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme);\n const params = {\n request: this.map._requestManager.transformRequest(url, ResourceType.Tile),\n uid: tile.uid,\n tileID: tile.tileID,\n zoom: tile.tileID.overscaledZ,\n tileSize: this.tileSize * tile.tileID.overscaleFactor(),\n type: this.type,\n source: this.id,\n pixelRatio: this.map.getPixelRatio(),\n showCollisionBoxes: this.map.showCollisionBoxes,\n promoteId: this.promoteId\n };\n params.request.collectResourceTiming = this._collectResourceTiming;\n let messageType: MessageType.loadTile | MessageType.reloadTile = MessageType.reloadTile;\n if (!tile.actor || tile.state === 'expired') {\n tile.actor = this.dispatcher.getActor();\n messageType = MessageType.loadTile;\n } else if (tile.state === 'loading') {\n return new Promise((resolve, reject) => {\n tile.reloadPromise = {resolve, reject};\n });\n }\n tile.abortController = new AbortController();\n try {\n const data = await tile.actor.sendAsync({type: messageType, data: params}, tile.abortController);\n delete tile.abortController;\n\n if (tile.aborted) {\n return;\n }\n this._afterTileLoadWorkerResponse(tile, data);\n } catch (err) {\n delete tile.abortController;\n\n if (tile.aborted) {\n return;\n }\n if (err && err.status !== 404) {\n throw err;\n }\n this._afterTileLoadWorkerResponse(tile, null);\n }\n }\n\n private _afterTileLoadWorkerResponse(tile: Tile, data: WorkerTileResult) {\n if (data && data.resourceTiming) {\n tile.resourceTiming = data.resourceTiming;\n }\n\n if (data && this.map._refreshExpiredTiles) {\n tile.setExpiryData(data);\n }\n tile.loadVectorData(data, this.map.painter);\n\n if (tile.reloadPromise) {\n const reloadPromise = tile.reloadPromise;\n tile.reloadPromise = null;\n this.loadTile(tile).then(reloadPromise.resolve).catch(reloadPromise.reject);\n }\n }\n\n async abortTile(tile: Tile): Promise {\n if (tile.abortController) {\n tile.abortController.abort();\n delete tile.abortController;\n }\n if (tile.actor) {\n await tile.actor.sendAsync({\n type: MessageType.abortTile,\n data: {uid: tile.uid, type: this.type, source: this.id}\n });\n }\n }\n\n async unloadTile(tile: Tile): Promise {\n tile.unloadVectorData();\n if (tile.actor) {\n await tile.actor.sendAsync({\n type: MessageType.removeTile,\n data: {\n uid: tile.uid,\n type: this.type,\n source: this.id}\n });\n }\n }\n\n hasTransition() {\n return false;\n }\n}\n","import {extend, pick} from '../util/util';\n\nimport {ImageRequest} from '../util/image_request';\n\nimport {ResourceType} from '../util/request_manager';\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport {loadTileJson} from './load_tilejson';\nimport {TileBounds} from './tile_bounds';\nimport {Texture} from '../render/texture';\n\nimport type {Source} from './source';\nimport type {OverscaledTileID} from './tile_id';\nimport type {Map} from '../ui/map';\nimport type {Dispatcher} from '../util/dispatcher';\nimport type {Tile} from './tile';\nimport type {\n RasterSourceSpecification,\n RasterDEMSourceSpecification\n} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * A source containing raster tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.)\n *\n * @group Sources\n *\n * @example\n * ```ts\n * map.addSource('raster-source', {\n * 'type': 'raster',\n * 'tiles': ['https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg'],\n * 'tileSize': 256,\n * });\n * ```\n *\n * @example\n * ```ts\n * map.addSource('wms-test-source', {\n * 'type': 'raster',\n * // use the tiles option to specify a WMS tile source URL\n * 'tiles': [\n * 'https://img.nj.gov/imagerywms/Natural2015?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=Natural2015'\n * ],\n * 'tileSize': 256\n * });\n * ```\n * @see [Add a raster tile source](https://maplibre.org/maplibre-gl-js/docs/examples/map-tiles/)\n * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/)\n * @see [Display a satellite map](https://maplibre.org/maplibre-gl-js/docs/examples/satellite-map/)\n */\nexport class RasterTileSource extends Evented implements Source {\n type: 'raster' | 'raster-dem';\n id: string;\n minzoom: number;\n maxzoom: number;\n url: string;\n scheme: string;\n tileSize: number;\n\n bounds: [number, number, number, number];\n tileBounds: TileBounds;\n roundZoom: boolean;\n dispatcher: Dispatcher;\n map: Map;\n tiles: Array;\n\n _loaded: boolean;\n _options: RasterSourceSpecification | RasterDEMSourceSpecification;\n _tileJSONRequest: AbortController;\n\n constructor(id: string, options: RasterSourceSpecification | RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super();\n this.id = id;\n this.dispatcher = dispatcher;\n this.setEventedParent(eventedParent);\n\n this.type = 'raster';\n this.minzoom = 0;\n this.maxzoom = 22;\n this.roundZoom = true;\n this.scheme = 'xyz';\n this.tileSize = 512;\n this._loaded = false;\n\n this._options = extend({type: 'raster'}, options);\n extend(this, pick(options, ['url', 'scheme', 'tileSize']));\n }\n\n async load() {\n this._loaded = false;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._tileJSONRequest = new AbortController();\n try {\n const tileJSON = await loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest);\n this._tileJSONRequest = null;\n this._loaded = true;\n if (tileJSON) {\n extend(this, tileJSON);\n if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);\n\n // `content` is included here to prevent a race condition where `Style#_updateSources` is called\n // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives\n // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'}));\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'content'}));\n }\n } catch (err) {\n this._tileJSONRequest = null;\n this.fire(new ErrorEvent(err));\n }\n }\n\n loaded(): boolean {\n return this._loaded;\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n }\n\n onRemove() {\n if (this._tileJSONRequest) {\n this._tileJSONRequest.abort();\n this._tileJSONRequest = null;\n }\n }\n\n setSourceProperty(callback: Function) {\n if (this._tileJSONRequest) {\n this._tileJSONRequest.abort();\n this._tileJSONRequest = null;\n }\n\n callback();\n\n this.load();\n }\n\n /**\n * Sets the source `tiles` property and re-renders the map.\n *\n * @param tiles - An array of one or more tile source URLs, as in the raster tiles spec (See the [Style Specification](https://maplibre.org/maplibre-style-spec/)\n */\n setTiles(tiles: Array): this {\n this.setSourceProperty(() => {\n this._options.tiles = tiles;\n });\n\n return this;\n }\n\n /**\n * Sets the source `url` property and re-renders the map.\n *\n * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`.\n */\n setUrl(url: string): this {\n this.setSourceProperty(() => {\n this.url = url;\n this._options.url = url;\n });\n\n return this;\n }\n\n serialize() {\n return extend({}, this._options);\n }\n\n hasTile(tileID: OverscaledTileID) {\n return !this.tileBounds || this.tileBounds.contains(tileID.canonical);\n }\n\n async loadTile(tile: Tile): Promise {\n const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme);\n tile.abortController = new AbortController();\n try {\n const response = await ImageRequest.getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), tile.abortController, this.map._refreshExpiredTiles);\n delete tile.abortController;\n if (tile.aborted) {\n tile.state = 'unloaded';\n return;\n }\n if (response && response.data) {\n if (this.map._refreshExpiredTiles && response.cacheControl && response.expires) {\n tile.setExpiryData({cacheControl: response.cacheControl, expires: response.expires});\n }\n const context = this.map.painter.context;\n const gl = context.gl;\n const img = response.data;\n tile.texture = this.map.painter.getTileTexture(img.width);\n if (tile.texture) {\n tile.texture.update(img, {useMipmap: true});\n } else {\n tile.texture = new Texture(context, img, gl.RGBA, {useMipmap: true});\n tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n }\n tile.state = 'loaded';\n }\n } catch (err) {\n delete tile.abortController;\n if (tile.aborted) {\n tile.state = 'unloaded';\n } else if (err) {\n tile.state = 'errored';\n throw err;\n }\n }\n }\n\n async abortTile(tile: Tile) {\n if (tile.abortController) {\n tile.abortController.abort();\n delete tile.abortController;\n }\n }\n\n async unloadTile(tile: Tile) {\n if (tile.texture) {\n this.map.painter.saveTileTexture(tile.texture);\n }\n }\n\n hasTransition() {\n return false;\n }\n}\n","export { getURL, getTileBBox, getMercCoords };\n\n\n/**\n * getURL\n *\n * @param {String} baseUrl Base url of the WMS server\n * @param {String} layer Layer name\n * @param {Number} x Tile coordinate x\n * @param {Number} y Tile coordinate y\n * @param {Number} z Tile zoom\n * @param {Object} [options]\n * @param {String} [options.format='image/png']\n * @param {String} [options.service='WMS']\n * @param {String} [options.version='1.1.1']\n * @param {String} [options.request='GetMap']\n * @param {String} [options.srs='EPSG:3857']\n * @param {Number} [options.width='256']\n * @param {Number} [options.height='256']\n * @returns {String} url\n * @example\n * var baseUrl = 'http://geodata.state.nj.us/imagerywms/Natural2015';\n * var layer = 'Natural2015';\n * var url = whoots.getURL(baseUrl, layer, 154308, 197167, 19);\n */\nfunction getURL(baseUrl, layer, x, y, z, options) {\n options = options || {};\n\n var url = baseUrl + '?' + [\n 'bbox=' + getTileBBox(x, y, z),\n 'format=' + (options.format || 'image/png'),\n 'service=' + (options.service || 'WMS'),\n 'version=' + (options.version || '1.1.1'),\n 'request=' + (options.request || 'GetMap'),\n 'srs=' + (options.srs || 'EPSG:3857'),\n 'width=' + (options.width || 256),\n 'height=' + (options.height || 256),\n 'layers=' + layer\n ].join('&');\n\n return url;\n}\n\n\n/**\n * getTileBBox\n *\n * @param {Number} x Tile coordinate x\n * @param {Number} y Tile coordinate y\n * @param {Number} z Tile zoom\n * @returns {String} String of the bounding box\n */\nfunction getTileBBox(x, y, z) {\n // for Google/OSM tile scheme we need to alter the y\n y = (Math.pow(2, z) - y - 1);\n\n var min = getMercCoords(x * 256, y * 256, z),\n max = getMercCoords((x + 1) * 256, (y + 1) * 256, z);\n\n return min[0] + ',' + min[1] + ',' + max[0] + ',' + max[1];\n}\n\n\n/**\n * getMercCoords\n *\n * @param {Number} x Pixel coordinate x\n * @param {Number} y Pixel coordinate y\n * @param {Number} z Tile zoom\n * @returns {Array} [x, y]\n */\nfunction getMercCoords(x, y, z) {\n var resolution = (2 * Math.PI * 6378137 / 256) / Math.pow(2, z),\n merc_x = (x * resolution - 2 * Math.PI * 6378137 / 2.0),\n merc_y = (y * resolution - 2 * Math.PI * 6378137 / 2.0);\n\n return [merc_x, merc_y];\n}\n","import {getTileBBox} from '@mapbox/whoots-js';\nimport {EXTENT} from '../data/extent';\nimport Point from '@mapbox/point-geometry';\nimport {MercatorCoordinate} from '../geo/mercator_coordinate';\nimport {register} from '../util/web_worker_transfer';\nimport {mat4} from 'gl-matrix';\nimport {ICanonicalTileID, IMercatorCoordinate} from '@maplibre/maplibre-gl-style-spec';\nimport {MAX_TILE_ZOOM, MIN_TILE_ZOOM} from '../util/util';\nimport {isInBoundsForTileZoomXY} from '../util/world_bounds';\n\n/**\n * A canonical way to define a tile ID\n */\nexport class CanonicalTileID implements ICanonicalTileID {\n z: number;\n x: number;\n y: number;\n key: string;\n\n constructor(z: number, x: number, y: number) {\n\n if (!isInBoundsForTileZoomXY(z, x, y)) {\n throw new Error(`x=${x}, y=${y}, z=${z} outside of bounds. 0<=x<${Math.pow(2, z)}, 0<=y<${Math.pow(2, z)} ${MIN_TILE_ZOOM}<=z<=${MAX_TILE_ZOOM} `);\n }\n\n this.z = z;\n this.x = x;\n this.y = y;\n this.key = calculateKey(0, z, z, x, y);\n }\n\n equals(id: ICanonicalTileID) {\n return this.z === id.z && this.x === id.x && this.y === id.y;\n }\n\n // given a list of urls, choose a url template and return a tile URL\n url(urls: Array, pixelRatio: number, scheme?: string | null) {\n const bbox = getTileBBox(this.x, this.y, this.z);\n const quadkey = getQuadkey(this.z, this.x, this.y);\n\n return urls[(this.x + this.y) % urls.length]\n .replace(/{prefix}/g, (this.x % 16).toString(16) + (this.y % 16).toString(16))\n .replace(/{z}/g, String(this.z))\n .replace(/{x}/g, String(this.x))\n .replace(/{y}/g, String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y))\n .replace(/{ratio}/g, pixelRatio > 1 ? '@2x' : '')\n .replace(/{quadkey}/g, quadkey)\n .replace(/{bbox-epsg-3857}/g, bbox);\n }\n\n isChildOf(parent: ICanonicalTileID) {\n const dz = this.z - parent.z;\n return dz > 0 && parent.x === (this.x >> dz) && parent.y === (this.y >> dz);\n }\n\n getTilePoint(coord: IMercatorCoordinate) {\n const tilesAtZoom = Math.pow(2, this.z);\n return new Point(\n (coord.x * tilesAtZoom - this.x) * EXTENT,\n (coord.y * tilesAtZoom - this.y) * EXTENT);\n }\n\n toString() {\n return `${this.z}/${this.x}/${this.y}`;\n }\n}\n\n/**\n * @internal\n * An unwrapped tile identifier\n */\nexport class UnwrappedTileID {\n wrap: number;\n canonical: CanonicalTileID;\n key: string;\n\n constructor(wrap: number, canonical: CanonicalTileID) {\n this.wrap = wrap;\n this.canonical = canonical;\n this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y);\n }\n}\n\n/**\n * An overscaled tile identifier\n */\nexport class OverscaledTileID {\n overscaledZ: number;\n wrap: number;\n canonical: CanonicalTileID;\n key: string;\n posMatrix: mat4;\n\n constructor(overscaledZ: number, wrap: number, z: number, x: number, y: number) {\n if (overscaledZ < z) throw new Error(`overscaledZ should be >= z; overscaledZ = ${overscaledZ}; z = ${z}`);\n this.overscaledZ = overscaledZ;\n this.wrap = wrap;\n this.canonical = new CanonicalTileID(z, +x, +y);\n this.key = calculateKey(wrap, overscaledZ, z, x, y);\n }\n\n clone() {\n return new OverscaledTileID(this.overscaledZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y);\n }\n\n equals(id: OverscaledTileID) {\n return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical);\n }\n\n scaledTo(targetZ: number) {\n if (targetZ > this.overscaledZ) throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`);\n const zDifference = this.canonical.z - targetZ;\n if (targetZ > this.canonical.z) {\n return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y);\n } else {\n return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);\n }\n }\n\n /*\n * calculateScaledKey is an optimization:\n * when withWrap == true, implements the same as this.scaledTo(z).key,\n * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key.\n */\n calculateScaledKey(targetZ: number, withWrap: boolean): string {\n if (targetZ > this.overscaledZ) throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`);\n const zDifference = this.canonical.z - targetZ;\n if (targetZ > this.canonical.z) {\n return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y);\n } else {\n return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);\n }\n }\n\n isChildOf(parent: OverscaledTileID) {\n if (parent.wrap !== this.wrap) {\n // We can't be a child if we're in a different world copy\n return false;\n }\n const zDifference = this.canonical.z - parent.canonical.z;\n // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined.\n return parent.overscaledZ === 0 || (\n parent.overscaledZ < this.overscaledZ &&\n parent.canonical.x === (this.canonical.x >> zDifference) &&\n parent.canonical.y === (this.canonical.y >> zDifference));\n }\n\n children(sourceMaxZoom: number) {\n if (this.overscaledZ >= sourceMaxZoom) {\n // return a single tile coord representing a an overscaled tile\n return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)];\n }\n\n const z = this.canonical.z + 1;\n const x = this.canonical.x * 2;\n const y = this.canonical.y * 2;\n return [\n new OverscaledTileID(z, this.wrap, z, x, y),\n new OverscaledTileID(z, this.wrap, z, x + 1, y),\n new OverscaledTileID(z, this.wrap, z, x, y + 1),\n new OverscaledTileID(z, this.wrap, z, x + 1, y + 1)\n ];\n }\n\n isLessThan(rhs: OverscaledTileID) {\n if (this.wrap < rhs.wrap) return true;\n if (this.wrap > rhs.wrap) return false;\n\n if (this.overscaledZ < rhs.overscaledZ) return true;\n if (this.overscaledZ > rhs.overscaledZ) return false;\n\n if (this.canonical.x < rhs.canonical.x) return true;\n if (this.canonical.x > rhs.canonical.x) return false;\n\n if (this.canonical.y < rhs.canonical.y) return true;\n return false;\n }\n\n wrapped() {\n return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y);\n }\n\n unwrapTo(wrap: number) {\n return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y);\n }\n\n overscaleFactor() {\n return Math.pow(2, this.overscaledZ - this.canonical.z);\n }\n\n toUnwrapped() {\n return new UnwrappedTileID(this.wrap, this.canonical);\n }\n\n toString() {\n return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`;\n }\n\n getTilePoint(coord: MercatorCoordinate) {\n return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y));\n }\n}\n\nfunction calculateKey(wrap: number, overscaledZ: number, z: number, x: number, y: number): string {\n wrap *= 2;\n if (wrap < 0) wrap = wrap * -1 - 1;\n const dim = 1 << z;\n return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36);\n}\n\nfunction getQuadkey(z, x, y) {\n let quadkey = '', mask;\n for (let i = z; i > 0; i--) {\n mask = 1 << (i - 1);\n quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0));\n }\n return quadkey;\n}\n\nregister('CanonicalTileID', CanonicalTileID);\nregister('OverscaledTileID', OverscaledTileID, {omit: ['posMatrix']});\n","import {MAX_TILE_ZOOM, MIN_TILE_ZOOM} from './util';\nimport {LngLat} from '../geo/lng_lat';\nimport {MercatorCoordinate} from '../geo/mercator_coordinate';\n\n/**\n * Returns true if a given tile zoom (Z), X, and Y are in the bounds of the world.\n * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive).\n * X and Y bounds are 0 (inclusive) to their respective zoom-dependent maxima (exclusive).\n *\n * @param zoom - the tile zoom (Z)\n * @param x - the tile X\n * @param y - the tile Y\n * @returns `true` if a given tile zoom, X, and Y are in the bounds of the world.\n */\nexport function isInBoundsForTileZoomXY(zoom: number, x: number, y: number): boolean {\n return !(\n zoom < MIN_TILE_ZOOM ||\n zoom > MAX_TILE_ZOOM ||\n y < 0 ||\n y >= Math.pow(2, zoom) ||\n x < 0 ||\n x >= Math.pow(2, zoom)\n );\n}\n\n/**\n * Returns true if a given zoom and `LngLat` are in the bounds of the world.\n * Does not wrap `LngLat` when checking if in bounds.\n * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive).\n * `LngLat` bounds are the mercator world's north-west corner (inclusive) to its south-east corner (exclusive).\n *\n * @param zoom - the tile zoom (Z)\n * @param LngLat - the `LngLat` object containing the longitude and latitude\n * @returns `true` if a given zoom and `LngLat` are in the bounds of the world.\n */\nexport function isInBoundsForZoomLngLat(zoom: number, lnglat: LngLat): boolean {\n const {x, y} = MercatorCoordinate.fromLngLat(lnglat);\n return !(\n zoom < MIN_TILE_ZOOM ||\n zoom > MAX_TILE_ZOOM ||\n y < 0 ||\n y >= 1 ||\n x < 0 ||\n x >= 1\n );\n}\n","import {RGBAImage} from '../util/image';\n\nimport {warnOnce} from '../util/util';\nimport {register} from '../util/web_worker_transfer';\n\n/**\n * The possible DEM encoding types\n */\nexport type DEMEncoding = 'mapbox' | 'terrarium' | 'custom'\n\n/**\n * DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders\n * data can be populated either from a pngraw image tile or from serialized data sent back from a worker. When data is initially\n * loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the\n * elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of\n * integer overflow when creating the texture used in the hillshadePrepare step.\n *\n * DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8\n * surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a\n * tile's edge without backfilling from neighboring tiles.\n */\nexport class DEMData {\n uid: string | number;\n data: Uint32Array;\n stride: number;\n dim: number;\n min: number;\n max: number;\n redFactor: number;\n greenFactor: number;\n blueFactor: number;\n baseShift: number;\n\n /**\n * Constructs a `DEMData` object\n * @param uid - the tile's unique id\n * @param data - RGBAImage data has uniform 1px padding on all sides: square tile edge size defines stride\n // and dim is calculated as stride - 2.\n * @param encoding - the encoding type of the data\n * @param redFactor - the red channel factor used to unpack the data, used for `custom` encoding only\n * @param greenFactor - the green channel factor used to unpack the data, used for `custom` encoding only\n * @param blueFactor - the blue channel factor used to unpack the data, used for `custom` encoding only\n * @param baseShift - the base shift used to unpack the data, used for `custom` encoding only\n */\n constructor(uid: string | number, data: RGBAImage | ImageData, encoding: DEMEncoding, redFactor = 1.0, greenFactor = 1.0, blueFactor = 1.0, baseShift = 0.0) {\n this.uid = uid;\n if (data.height !== data.width) throw new RangeError('DEM tiles must be square');\n if (encoding && !['mapbox', 'terrarium', 'custom'].includes(encoding)) {\n warnOnce(`\"${encoding}\" is not a valid encoding type. Valid types include \"mapbox\", \"terrarium\" and \"custom\".`);\n return;\n }\n this.stride = data.height;\n const dim = this.dim = data.height - 2;\n this.data = new Uint32Array(data.data.buffer);\n switch (encoding) {\n case 'terrarium':\n // unpacking formula for mapzen terrarium:\n // https://aws.amazon.com/public-datasets/terrain/\n this.redFactor = 256.0;\n this.greenFactor = 1.0;\n this.blueFactor = 1.0 / 256.0;\n this.baseShift = 32768.0;\n break;\n case 'custom':\n this.redFactor = redFactor;\n this.greenFactor = greenFactor;\n this.blueFactor = blueFactor;\n this.baseShift = baseShift;\n break;\n case 'mapbox':\n default:\n // unpacking formula for mapbox.terrain-rgb:\n // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb\n this.redFactor = 6553.6;\n this.greenFactor = 25.6;\n this.blueFactor = 0.1;\n this.baseShift = 10000.0;\n break;\n }\n\n // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of pixels around the image\n // with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring\n // tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder\n for (let x = 0; x < dim; x++) {\n // left vertical border\n this.data[this._idx(-1, x)] = this.data[this._idx(0, x)];\n // right vertical border\n this.data[this._idx(dim, x)] = this.data[this._idx(dim - 1, x)];\n // left horizontal border\n this.data[this._idx(x, -1)] = this.data[this._idx(x, 0)];\n // right horizontal border\n this.data[this._idx(x, dim)] = this.data[this._idx(x, dim - 1)];\n }\n // corners\n this.data[this._idx(-1, -1)] = this.data[this._idx(0, 0)];\n this.data[this._idx(dim, -1)] = this.data[this._idx(dim - 1, 0)];\n this.data[this._idx(-1, dim)] = this.data[this._idx(0, dim - 1)];\n this.data[this._idx(dim, dim)] = this.data[this._idx(dim - 1, dim - 1)];\n\n // calculate min/max values\n this.min = Number.MAX_SAFE_INTEGER;\n this.max = Number.MIN_SAFE_INTEGER;\n for (let x = 0; x < dim; x++) {\n for (let y = 0; y < dim; y++) {\n const ele = this.get(x, y);\n if (ele > this.max) this.max = ele;\n if (ele < this.min) this.min = ele;\n }\n }\n }\n\n get(x: number, y: number) {\n const pixels = new Uint8Array(this.data.buffer);\n const index = this._idx(x, y) * 4;\n return this.unpack(pixels[index], pixels[index + 1], pixels[index + 2]);\n }\n\n getUnpackVector() {\n return [this.redFactor, this.greenFactor, this.blueFactor, this.baseShift];\n }\n\n _idx(x: number, y: number) {\n if (x < -1 || x >= this.dim + 1 || y < -1 || y >= this.dim + 1) throw new RangeError('out of range source coordinates for DEM data');\n return (y + 1) * this.stride + (x + 1);\n }\n\n unpack(r: number, g: number, b: number) {\n return (r * this.redFactor + g * this.greenFactor + b * this.blueFactor - this.baseShift);\n }\n\n getPixels() {\n return new RGBAImage({width: this.stride, height: this.stride}, new Uint8Array(this.data.buffer));\n }\n\n backfillBorder(borderTile: DEMData, dx: number, dy: number) {\n if (this.dim !== borderTile.dim) throw new Error('dem dimension mismatch');\n\n let xMin = dx * this.dim,\n xMax = dx * this.dim + this.dim,\n yMin = dy * this.dim,\n yMax = dy * this.dim + this.dim;\n\n switch (dx) {\n case -1:\n xMin = xMax - 1;\n break;\n case 1:\n xMax = xMin + 1;\n break;\n }\n\n switch (dy) {\n case -1:\n yMin = yMax - 1;\n break;\n case 1:\n yMax = yMin + 1;\n break;\n }\n\n const ox = -dx * this.dim;\n const oy = -dy * this.dim;\n for (let y = yMin; y < yMax; y++) {\n for (let x = xMin; x < xMax; x++) {\n this.data[this._idx(x, y)] = borderTile.data[this._idx(x + ox, y + oy)];\n }\n }\n }\n}\n\nregister('DEMData', DEMData);\n","import {ImageRequest} from '../util/image_request';\nimport {ResourceType} from '../util/request_manager';\nimport {extend, isImageBitmap, readImageUsingVideoFrame} from '../util/util';\nimport {Evented} from '../util/evented';\nimport {browser} from '../util/browser';\nimport {offscreenCanvasSupported} from '../util/offscreen_canvas_supported';\nimport {OverscaledTileID} from './tile_id';\nimport {RasterTileSource} from './raster_tile_source';\n// ensure DEMData is registered for worker transfer on main thread:\nimport '../data/dem_data';\nimport type {DEMEncoding} from '../data/dem_data';\n\nimport type {Source} from './source';\nimport type {Dispatcher} from '../util/dispatcher';\nimport type {Tile} from './tile';\nimport type {RasterDEMSourceSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {isOffscreenCanvasDistorted} from '../util/offscreen_canvas_distorted';\nimport {RGBAImage} from '../util/image';\nimport {MessageType} from '../util/actor_messages';\n\n/**\n * A source containing raster DEM tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.)\n * This source can be used to show hillshading and 3D terrain\n *\n * @group Sources\n *\n * @example\n * ```ts\n * map.addSource('raster-dem-source', {\n * type: 'raster-dem',\n * url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json',\n * tileSize: 256\n * });\n * ```\n * @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/)\n */\nexport class RasterDEMTileSource extends RasterTileSource implements Source {\n encoding: DEMEncoding;\n redFactor?: number;\n greenFactor?: number;\n blueFactor?: number;\n baseShift?: number;\n\n constructor(id: string, options: RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super(id, options, dispatcher, eventedParent);\n this.type = 'raster-dem';\n this.maxzoom = 22;\n this._options = extend({type: 'raster-dem'}, options);\n this.encoding = options.encoding || 'mapbox';\n this.redFactor = options.redFactor;\n this.greenFactor = options.greenFactor;\n this.blueFactor = options.blueFactor;\n this.baseShift = options.baseShift;\n }\n\n override async loadTile(tile: Tile): Promise {\n const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme);\n const request = this.map._requestManager.transformRequest(url, ResourceType.Tile);\n tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);\n tile.abortController = new AbortController();\n try {\n const response = await ImageRequest.getImage(request, tile.abortController, this.map._refreshExpiredTiles);\n delete tile.abortController;\n if (tile.aborted) {\n tile.state = 'unloaded';\n return;\n }\n if (response && response.data) {\n const img = response.data;\n if (this.map._refreshExpiredTiles && response.cacheControl && response.expires) {\n tile.setExpiryData({cacheControl: response.cacheControl, expires: response.expires});\n }\n const transfer = isImageBitmap(img) && offscreenCanvasSupported();\n const rawImageData = transfer ? img : await this.readImageNow(img);\n const params = {\n type: this.type,\n uid: tile.uid,\n source: this.id,\n rawImageData,\n encoding: this.encoding,\n redFactor: this.redFactor,\n greenFactor: this.greenFactor,\n blueFactor: this.blueFactor,\n baseShift: this.baseShift\n };\n\n if (!tile.actor || tile.state === 'expired') {\n tile.actor = this.dispatcher.getActor();\n /* eslint-disable require-atomic-updates */\n const data = await tile.actor.sendAsync({type: MessageType.loadDEMTile, data: params});\n tile.dem = data;\n tile.needsHillshadePrepare = true;\n tile.needsTerrainPrepare = true;\n tile.state = 'loaded';\n /* eslint-enable require-atomic-updates */\n }\n }\n } catch (err) {\n delete tile.abortController;\n if (tile.aborted) {\n tile.state = 'unloaded';\n } else if (err) {\n tile.state = 'errored';\n throw err;\n }\n }\n }\n\n async readImageNow(img: ImageBitmap | HTMLImageElement): Promise {\n if (typeof VideoFrame !== 'undefined' && isOffscreenCanvasDistorted()) {\n const width = img.width + 2;\n const height = img.height + 2;\n try {\n return new RGBAImage({width, height}, await readImageUsingVideoFrame(img, -1, -1, width, height));\n } catch (e) {\n // fall-back to browser canvas decoding\n }\n }\n return browser.getImageData(img, 1);\n }\n\n _getNeighboringTiles(tileID: OverscaledTileID) {\n const canonical = tileID.canonical;\n const dim = Math.pow(2, canonical.z);\n\n const px = (canonical.x - 1 + dim) % dim;\n const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap;\n const nx = (canonical.x + 1 + dim) % dim;\n const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap;\n\n const neighboringTiles = {};\n // add adjacent tiles\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = {backfilled: false};\n\n // Add upper neighboringTiles\n if (canonical.y > 0) {\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = {backfilled: false};\n }\n // Add lower neighboringTiles\n if (canonical.y + 1 < dim) {\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = {backfilled: false};\n }\n\n return neighboringTiles;\n }\n\n async unloadTile(tile: Tile) {\n if (tile.demTexture) this.map.painter.saveTileTexture(tile.demTexture);\n if (tile.fbo) {\n tile.fbo.destroy();\n delete tile.fbo;\n }\n if (tile.dem) delete tile.dem;\n delete tile.neighboringTiles;\n\n tile.state = 'unloaded';\n if (tile.actor) {\n await tile.actor.sendAsync({type: MessageType.removeDEMTile, data: {type: this.type, uid: tile.uid, source: this.id}});\n }\n }\n}\n","import {Event, ErrorEvent, Evented} from '../util/evented';\n\nimport {extend, warnOnce} from '../util/util';\nimport {EXTENT} from '../data/extent';\nimport {ResourceType} from '../util/request_manager';\nimport {browser} from '../util/browser';\n\nimport type {Source} from './source';\nimport type {Map} from '../ui/map';\nimport type {Dispatcher} from '../util/dispatcher';\nimport type {Tile} from './tile';\nimport type {Actor} from '../util/actor';\nimport type {GeoJSONSourceSpecification, PromoteIdSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {GeoJSONSourceDiff} from './geojson_source_diff';\nimport type {GeoJSONWorkerOptions, LoadGeoJSONParameters} from './geojson_worker_source';\nimport {MessageType} from '../util/actor_messages';\n\n/**\n * Options object for GeoJSONSource.\n */\nexport type GeoJSONSourceOptions = GeoJSONSourceSpecification & {\n workerOptions?: GeoJSONWorkerOptions;\n collectResourceTiming?: boolean;\n data: GeoJSON.GeoJSON | string;\n}\n\nexport type GeoJSONSourceInternalOptions = {\n data?: GeoJSON.GeoJSON | string | undefined;\n cluster?: boolean;\n clusterMaxZoom?: number;\n clusterRadius?: number;\n clusterMinPoints?: number;\n generateId?: boolean;\n}\n\n/**\n * The cluster options to set\n */\nexport type SetClusterOptions = {\n /**\n * Whether or not to cluster\n */\n cluster?: boolean;\n /**\n * The cluster's max zoom\n */\n clusterMaxZoom?: number;\n /**\n * The cluster's radius\n */\n clusterRadius?: number;\n}\n\n/**\n * A source containing GeoJSON.\n * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-geojson) for detailed documentation of options.)\n *\n * @group Sources\n *\n * @example\n * ```ts\n * map.addSource('some id', {\n * type: 'geojson',\n * data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'\n * });\n * ```\n *\n * @example\n * ```ts\n * map.addSource('some id', {\n * type: 'geojson',\n * data: {\n * \"type\": \"FeatureCollection\",\n * \"features\": [{\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [\n * -76.53063297271729,\n * 39.18174077994108\n * ]\n * }\n * }]\n * }\n * });\n * ```\n *\n * @example\n * ```ts\n * map.getSource('some id').setData({\n * \"type\": \"FeatureCollection\",\n * \"features\": [{\n * \"type\": \"Feature\",\n * \"properties\": { \"name\": \"Null Island\" },\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [ 0, 0 ]\n * }\n * }]\n * });\n * ```\n * @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-markers/)\n * @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-line/)\n * @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js/docs/examples/heatmap-layer/)\n * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/)\n */\nexport class GeoJSONSource extends Evented implements Source {\n type: 'geojson';\n id: string;\n minzoom: number;\n maxzoom: number;\n tileSize: number;\n attribution: string;\n promoteId: PromoteIdSpecification;\n\n isTileClipped: boolean;\n reparseOverscaled: boolean;\n _data: GeoJSON.GeoJSON | string | undefined;\n _options: GeoJSONSourceInternalOptions;\n workerOptions: GeoJSONWorkerOptions;\n map: Map;\n actor: Actor;\n _pendingLoads: number;\n _collectResourceTiming: boolean;\n _removed: boolean;\n\n /** @internal */\n constructor(id: string, options: GeoJSONSourceOptions, dispatcher: Dispatcher, eventedParent: Evented) {\n super();\n\n this.id = id;\n\n // `type` is a property rather than a constant to make it easy for 3rd\n // parties to use GeoJSONSource to build their own source types.\n this.type = 'geojson';\n\n this.minzoom = 0;\n this.maxzoom = 18;\n this.tileSize = 512;\n this.isTileClipped = true;\n this.reparseOverscaled = true;\n this._removed = false;\n this._pendingLoads = 0;\n\n this.actor = dispatcher.getActor();\n this.setEventedParent(eventedParent);\n\n this._data = (options.data as any);\n this._options = extend({}, options);\n\n this._collectResourceTiming = options.collectResourceTiming;\n\n if (options.maxzoom !== undefined) this.maxzoom = options.maxzoom;\n if (options.type) this.type = options.type;\n if (options.attribution) this.attribution = options.attribution;\n this.promoteId = options.promoteId;\n\n const scale = EXTENT / this.tileSize;\n\n if (options.clusterMaxZoom !== undefined && this.maxzoom <= options.clusterMaxZoom) {\n warnOnce(`The maxzoom value \"${this.maxzoom}\" is expected to be greater than the clusterMaxZoom value \"${options.clusterMaxZoom}\".`);\n }\n\n // sent to the worker, along with `url: ...` or `data: literal geojson`,\n // so that it can load/parse/index the geojson data\n // extending with `options.workerOptions` helps to make it easy for\n // third-party sources to hack/reuse GeoJSONSource.\n this.workerOptions = extend({\n source: this.id,\n cluster: options.cluster || false,\n geojsonVtOptions: {\n buffer: (options.buffer !== undefined ? options.buffer : 128) * scale,\n tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale,\n extent: EXTENT,\n maxZoom: this.maxzoom,\n lineMetrics: options.lineMetrics || false,\n generateId: options.generateId || false\n },\n superclusterOptions: {\n maxZoom: options.clusterMaxZoom !== undefined ? options.clusterMaxZoom : this.maxzoom - 1,\n minPoints: Math.max(2, options.clusterMinPoints || 2),\n extent: EXTENT,\n radius: (options.clusterRadius || 50) * scale,\n log: false,\n generateId: options.generateId || false\n },\n clusterProperties: options.clusterProperties,\n filter: options.filter\n }, options.workerOptions);\n\n // send the promoteId to the worker to have more flexible updates, but only if it is a string\n if (typeof this.promoteId === 'string') {\n this.workerOptions.promoteId = this.promoteId;\n }\n }\n\n async load() {\n await this._updateWorkerData();\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n }\n\n /**\n * Sets the GeoJSON data and re-renders the map.\n *\n * @param data - A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.\n */\n setData(data: GeoJSON.GeoJSON | string): this {\n this._data = data;\n this._updateWorkerData();\n\n return this;\n }\n\n /**\n * Updates the source's GeoJSON, and re-renders the map.\n *\n * For sources with lots of features, this method can be used to make updates more quickly.\n *\n * This approach requires unique IDs for every feature in the source. The IDs can either be specified on the feature,\n * or by using the promoteId option to specify which property should be used as the ID.\n *\n * It is an error to call updateData on a source that did not have unique IDs for each of its features already.\n *\n * Updates are applied on a best-effort basis, updating an ID that does not exist will not result in an error.\n *\n * @param diff - The changes that need to be applied.\n */\n updateData(diff: GeoJSONSourceDiff): this {\n this._updateWorkerData(diff);\n\n return this;\n }\n\n /**\n * Allows to get the source's actual GeoJSON data.\n *\n * @returns a promise which resolves to the source's actual GeoJSON data\n */\n async getData(): Promise {\n const options: LoadGeoJSONParameters = extend({type: this.type}, this.workerOptions);\n return this.actor.sendAsync({type: MessageType.getData, data: options});\n }\n\n /**\n * To disable/enable clustering on the source options\n * @param options - The options to set\n * @example\n * ```ts\n * map.getSource('some id').setClusterOptions({cluster: false});\n * map.getSource('some id').setClusterOptions({cluster: false, clusterRadius: 50, clusterMaxZoom: 14});\n * ```\n */\n setClusterOptions(options: SetClusterOptions): this {\n this.workerOptions.cluster = options.cluster;\n if (options) {\n if (options.clusterRadius !== undefined) this.workerOptions.superclusterOptions.radius = options.clusterRadius;\n if (options.clusterMaxZoom !== undefined) this.workerOptions.superclusterOptions.maxZoom = options.clusterMaxZoom;\n }\n this._updateWorkerData();\n return this;\n }\n\n /**\n * For clustered sources, fetches the zoom at which the given cluster expands.\n *\n * @param clusterId - The value of the cluster's `cluster_id` property.\n * @returns a promise that is resolved with the zoom number\n */\n getClusterExpansionZoom(clusterId: number): Promise {\n return this.actor.sendAsync({type: MessageType.getClusterExpansionZoom, data: {type: this.type, clusterId, source: this.id}});\n }\n\n /**\n * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).\n *\n * @param clusterId - The value of the cluster's `cluster_id` property.\n * @returns a promise that is resolved when the features are retrieved\n */\n getClusterChildren(clusterId: number): Promise> {\n return this.actor.sendAsync({type: MessageType.getClusterChildren, data: {type: this.type, clusterId, source: this.id}});\n }\n\n /**\n * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).\n *\n * @param clusterId - The value of the cluster's `cluster_id` property.\n * @param limit - The maximum number of features to return.\n * @param offset - The number of features to skip (e.g. for pagination).\n * @returns a promise that is resolved when the features are retrieved\n * @example\n * Retrieve cluster leaves on click\n * ```ts\n * map.on('click', 'clusters', (e) => {\n * let features = map.queryRenderedFeatures(e.point, {\n * layers: ['clusters']\n * });\n *\n * let clusterId = features[0].properties.cluster_id;\n * let pointCount = features[0].properties.point_count;\n * let clusterSource = map.getSource('clusters');\n *\n * const features = await clusterSource.getClusterLeaves(clusterId, pointCount);\n * // Print cluster leaves in the console\n * console.log('Cluster leaves:', features);\n * });\n * ```\n */\n getClusterLeaves(clusterId: number, limit: number, offset: number): Promise> {\n return this.actor.sendAsync({type: MessageType.getClusterLeaves, data: {\n type: this.type,\n source: this.id,\n clusterId,\n limit,\n offset\n }});\n }\n\n /**\n * Responsible for invoking WorkerSource's geojson.loadData target, which\n * handles loading the geojson data and preparing to serve it up as tiles,\n * using geojson-vt or supercluster as appropriate.\n * @param diff - the diff object\n */\n async _updateWorkerData(diff?: GeoJSONSourceDiff) {\n const options: LoadGeoJSONParameters = extend({type: this.type}, this.workerOptions);\n if (diff) {\n options.dataDiff = diff;\n } else if (typeof this._data === 'string') {\n options.request = this.map._requestManager.transformRequest(browser.resolveURL(this._data as string), ResourceType.Source);\n options.request.collectResourceTiming = this._collectResourceTiming;\n } else {\n options.data = JSON.stringify(this._data);\n }\n this._pendingLoads++;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n try {\n const result = await this.actor.sendAsync({type: MessageType.loadData, data: options});\n this._pendingLoads--;\n if (this._removed || result.abandoned) {\n this.fire(new Event('dataabort', {dataType: 'source'}));\n return;\n }\n\n let resourceTiming: PerformanceResourceTiming[] = null;\n if (result.resourceTiming && result.resourceTiming[this.id]) {\n resourceTiming = result.resourceTiming[this.id].slice(0);\n }\n\n const data: any = {dataType: 'source'};\n if (this._collectResourceTiming && resourceTiming && resourceTiming.length > 0) {\n extend(data, {resourceTiming});\n }\n\n // although GeoJSON sources contain no metadata, we fire this event to let the SourceCache\n // know its ok to start requesting tiles.\n this.fire(new Event('data', {...data, sourceDataType: 'metadata'}));\n this.fire(new Event('data', {...data, sourceDataType: 'content'}));\n } catch (err) {\n this._pendingLoads--;\n if (this._removed) {\n this.fire(new Event('dataabort', {dataType: 'source'}));\n return;\n }\n this.fire(new ErrorEvent(err));\n }\n }\n\n loaded(): boolean {\n return this._pendingLoads === 0;\n }\n\n async loadTile(tile: Tile): Promise {\n const message = !tile.actor ? MessageType.loadTile : MessageType.reloadTile;\n tile.actor = this.actor;\n const params = {\n type: this.type,\n uid: tile.uid,\n tileID: tile.tileID,\n zoom: tile.tileID.overscaledZ,\n maxZoom: this.maxzoom,\n tileSize: this.tileSize,\n source: this.id,\n pixelRatio: this.map.getPixelRatio(),\n showCollisionBoxes: this.map.showCollisionBoxes,\n promoteId: this.promoteId\n };\n\n tile.abortController = new AbortController();\n const data = await this.actor.sendAsync({type: message, data: params}, tile.abortController);\n delete tile.abortController;\n tile.unloadVectorData();\n\n if (!tile.aborted) {\n tile.loadVectorData(data, this.map.painter, message === MessageType.reloadTile);\n }\n }\n\n async abortTile(tile: Tile) {\n if (tile.abortController) {\n tile.abortController.abort();\n delete tile.abortController;\n }\n tile.aborted = true;\n }\n\n async unloadTile(tile: Tile) {\n tile.unloadVectorData();\n await this.actor.sendAsync({type: MessageType.removeTile, data: {uid: tile.uid, type: this.type, source: this.id}});\n }\n\n onRemove() {\n this._removed = true;\n this.actor.sendAsync({type: MessageType.removeSource, data: {type: this.type, source: this.id}});\n }\n\n serialize(): GeoJSONSourceSpecification {\n return extend({}, this._options, {\n type: this.type,\n data: this._data\n });\n }\n\n hasTransition() {\n return false;\n }\n}\n","import {createLayout} from '../util/struct_array';\n\nexport default createLayout([\n {name: 'a_pos', type: 'Int16', components: 2},\n {name: 'a_texture_pos', type: 'Int16', components: 2}\n]);\n","import {CanonicalTileID} from './tile_id';\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport {ImageRequest} from '../util/image_request';\nimport {ResourceType} from '../util/request_manager';\nimport {EXTENT} from '../data/extent';\nimport {RasterBoundsArray} from '../data/array_types.g';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport {SegmentVector} from '../data/segment';\nimport {Texture} from '../render/texture';\nimport {MercatorCoordinate} from '../geo/mercator_coordinate';\n\nimport type {Source} from './source';\nimport type {CanvasSourceSpecification} from './canvas_source';\nimport type {Map} from '../ui/map';\nimport type {Dispatcher} from '../util/dispatcher';\nimport type {Tile} from './tile';\nimport type {VertexBuffer} from '../gl/vertex_buffer';\nimport type {\n ImageSourceSpecification,\n VideoSourceSpecification\n} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * Four geographical coordinates,\n * represented as arrays of longitude and latitude numbers, which define the corners of the image.\n * The coordinates start at the top left corner of the image and proceed in clockwise order.\n * They do not have to represent a rectangle.\n */\nexport type Coordinates = [[number, number], [number, number], [number, number], [number, number]];\n\n/**\n * The options object for the {@link ImageSource#updateImage} method\n */\nexport type UpdateImageOptions = {\n /**\n * Required image URL.\n */\n url: string;\n /**\n * The image coordinates\n */\n coordinates?: Coordinates;\n}\n\n/**\n * A data source containing an image.\n * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-image) for detailed documentation of options.)\n *\n * @group Sources\n *\n * @example\n * ```ts\n * // add to map\n * map.addSource('some id', {\n * type: 'image',\n * url: 'https://www.maplibre.org/images/foo.png',\n * coordinates: [\n * [-76.54, 39.18],\n * [-76.52, 39.18],\n * [-76.52, 39.17],\n * [-76.54, 39.17]\n * ]\n * });\n *\n * // update coordinates\n * let mySource = map.getSource('some id');\n * mySource.setCoordinates([\n * [-76.54335737228394, 39.18579907229748],\n * [-76.52803659439087, 39.1838364847587],\n * [-76.5295386314392, 39.17683392507606],\n * [-76.54520273208618, 39.17876344106642]\n * ]);\n *\n * // update url and coordinates simultaneously\n * mySource.updateImage({\n * url: 'https://www.maplibre.org/images/bar.png',\n * coordinates: [\n * [-76.54335737228394, 39.18579907229748],\n * [-76.52803659439087, 39.1838364847587],\n * [-76.5295386314392, 39.17683392507606],\n * [-76.54520273208618, 39.17876344106642]\n * ]\n * })\n *\n * map.removeSource('some id'); // remove\n * ```\n */\nexport class ImageSource extends Evented implements Source {\n type: string;\n id: string;\n minzoom: number;\n maxzoom: number;\n tileSize: number;\n url: string;\n\n coordinates: Coordinates;\n tiles: {[_: string]: Tile};\n options: any;\n dispatcher: Dispatcher;\n map: Map;\n texture: Texture | null;\n image: HTMLImageElement | ImageBitmap;\n tileID: CanonicalTileID;\n _boundsArray: RasterBoundsArray;\n boundsBuffer: VertexBuffer;\n boundsSegments: SegmentVector;\n _loaded: boolean;\n _request: AbortController;\n\n /** @internal */\n constructor(id: string, options: ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super();\n this.id = id;\n this.dispatcher = dispatcher;\n this.coordinates = options.coordinates;\n\n this.type = 'image';\n this.minzoom = 0;\n this.maxzoom = 22;\n this.tileSize = 512;\n this.tiles = {};\n this._loaded = false;\n\n this.setEventedParent(eventedParent);\n\n this.options = options;\n }\n\n async load(newCoordinates?: Coordinates): Promise {\n this._loaded = false;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n\n this.url = this.options.url;\n\n this._request = new AbortController();\n try {\n const image = await ImageRequest.getImage(this.map._requestManager.transformRequest(this.url, ResourceType.Image), this._request);\n this._request = null;\n this._loaded = true;\n\n if (image && image.data) {\n this.image = image.data;\n if (newCoordinates) {\n this.coordinates = newCoordinates;\n }\n this._finishLoading();\n }\n } catch (err) {\n this._request = null;\n this._loaded = true;\n this.fire(new ErrorEvent(err));\n }\n }\n\n loaded(): boolean {\n return this._loaded;\n }\n\n /**\n * Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing,\n * set the `raster-fade-duration` paint property on the raster layer to 0.\n *\n * @param options - The options object.\n */\n updateImage(options: UpdateImageOptions): this {\n if (!options.url) {\n return this;\n }\n\n if (this._request) {\n this._request.abort();\n this._request = null;\n }\n\n this.options.url = options.url;\n this.load(options.coordinates).finally(() => { this.texture = null; });\n return this;\n }\n\n _finishLoading() {\n if (this.map) {\n this.setCoordinates(this.coordinates);\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'}));\n }\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n }\n\n onRemove() {\n if (this._request) {\n this._request.abort();\n this._request = null;\n }\n }\n\n /**\n * Sets the image's coordinates and re-renders the map.\n *\n * @param coordinates - Four geographical coordinates,\n * represented as arrays of longitude and latitude numbers, which define the corners of the image.\n * The coordinates start at the top left corner of the image and proceed in clockwise order.\n * They do not have to represent a rectangle.\n */\n setCoordinates(coordinates: Coordinates): this {\n this.coordinates = coordinates;\n\n // Calculate which mercator tile is suitable for rendering the video in\n // and create a buffer with the corner coordinates. These coordinates\n // may be outside the tile, because raster tiles aren't clipped when rendering.\n\n // transform the geo coordinates into (zoom 0) tile space coordinates\n const cornerCoords = coordinates.map(MercatorCoordinate.fromLngLat);\n\n // Compute the coordinates of the tile we'll use to hold this image's\n // render data\n this.tileID = getCoordinatesCenterTileID(cornerCoords);\n\n // Constrain min/max zoom to our tile's zoom level in order to force\n // SourceCache to request this tile (no matter what the map's zoom\n // level)\n this.minzoom = this.maxzoom = this.tileID.z;\n\n // Transform the corner coordinates into the coordinate space of our\n // tile.\n const tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round());\n\n this._boundsArray = new RasterBoundsArray();\n this._boundsArray.emplaceBack(tileCoords[0].x, tileCoords[0].y, 0, 0);\n this._boundsArray.emplaceBack(tileCoords[1].x, tileCoords[1].y, EXTENT, 0);\n this._boundsArray.emplaceBack(tileCoords[3].x, tileCoords[3].y, 0, EXTENT);\n this._boundsArray.emplaceBack(tileCoords[2].x, tileCoords[2].y, EXTENT, EXTENT);\n\n if (this.boundsBuffer) {\n this.boundsBuffer.destroy();\n delete this.boundsBuffer;\n }\n\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'content'}));\n return this;\n }\n\n prepare() {\n if (Object.keys(this.tiles).length === 0 || !this.image) {\n return;\n }\n\n const context = this.map.painter.context;\n const gl = context.gl;\n\n if (!this.boundsBuffer) {\n this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);\n }\n\n if (!this.boundsSegments) {\n this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n }\n\n if (!this.texture) {\n this.texture = new Texture(context, this.image, gl.RGBA);\n this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n }\n\n let newTilesLoaded = false;\n for (const w in this.tiles) {\n const tile = this.tiles[w];\n if (tile.state !== 'loaded') {\n tile.state = 'loaded';\n tile.texture = this.texture;\n newTilesLoaded = true;\n }\n }\n\n if (newTilesLoaded) {\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'idle', sourceId: this.id}));\n }\n }\n\n async loadTile(tile: Tile): Promise {\n // We have a single tile -- whose coordinates are this.tileID -- that\n // covers the image we want to render. If that's the one being\n // requested, set it up with the image; otherwise, mark the tile as\n // `errored` to indicate that we have no data for it.\n // If the world wraps, we may have multiple \"wrapped\" copies of the\n // single tile.\n if (this.tileID && this.tileID.equals(tile.tileID.canonical)) {\n this.tiles[String(tile.tileID.wrap)] = tile;\n tile.buckets = {};\n } else {\n tile.state = 'errored';\n }\n }\n\n serialize(): ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification {\n return {\n type: 'image',\n url: this.options.url,\n coordinates: this.coordinates\n };\n }\n\n hasTransition() {\n return false;\n }\n}\n\n/**\n * Given a list of coordinates, get their center as a coordinate.\n *\n * @returns centerpoint\n * @internal\n */\nexport function getCoordinatesCenterTileID(coords: Array) {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (const coord of coords) {\n minX = Math.min(minX, coord.x);\n minY = Math.min(minY, coord.y);\n maxX = Math.max(maxX, coord.x);\n maxY = Math.max(maxY, coord.y);\n }\n\n const dx = maxX - minX;\n const dy = maxY - minY;\n const dMax = Math.max(dx, dy);\n const zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2));\n const tilesAtZoom = Math.pow(2, zoom);\n\n return new CanonicalTileID(\n zoom,\n Math.floor((minX + maxX) / 2 * tilesAtZoom),\n Math.floor((minY + maxY) / 2 * tilesAtZoom));\n}\n","import {getVideo} from '../util/ajax';\nimport {ResourceType} from '../util/request_manager';\n\nimport {ImageSource} from './image_source';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport {SegmentVector} from '../data/segment';\nimport {Texture} from '../render/texture';\nimport {Event, ErrorEvent} from '../util/evented';\nimport {ValidationError} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {Map} from '../ui/map';\nimport type {Dispatcher} from '../util/dispatcher';\nimport type {Evented} from '../util/evented';\nimport type {VideoSourceSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * A data source containing video.\n * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-video) for detailed documentation of options.)\n *\n * @group Sources\n *\n * @example\n * ```ts\n * // add to map\n * map.addSource('some id', {\n * type: 'video',\n * url: [\n * 'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4',\n * 'https://www.mapbox.com/blog/assets/baltimore-smoke.webm'\n * ],\n * coordinates: [\n * [-76.54, 39.18],\n * [-76.52, 39.18],\n * [-76.52, 39.17],\n * [-76.54, 39.17]\n * ]\n * });\n *\n * // update\n * let mySource = map.getSource('some id');\n * mySource.setCoordinates([\n * [-76.54335737228394, 39.18579907229748],\n * [-76.52803659439087, 39.1838364847587],\n * [-76.5295386314392, 39.17683392507606],\n * [-76.54520273208618, 39.17876344106642]\n * ]);\n *\n * map.removeSource('some id'); // remove\n * ```\n * @see [Add a video](https://maplibre.org/maplibre-gl-js/docs/examples/video-on-a-map/)\n *\n * Note that when rendered as a raster layer, the layer's `raster-fade-duration` property will cause the video to fade in.\n * This happens when playback is started, paused and resumed, or when the video's coordinates are updated. To avoid this behavior,\n * set the layer's `raster-fade-duration` property to `0`.\n */\nexport class VideoSource extends ImageSource {\n options: VideoSourceSpecification;\n urls: Array;\n video: HTMLVideoElement;\n roundZoom: boolean;\n\n constructor(id: string, options: VideoSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super(id, options, dispatcher, eventedParent);\n this.roundZoom = true;\n this.type = 'video';\n this.options = options;\n }\n\n async load() {\n this._loaded = false;\n const options = this.options;\n\n this.urls = [];\n for (const url of options.urls) {\n this.urls.push(this.map._requestManager.transformRequest(url, ResourceType.Source).url);\n }\n try {\n const video = await getVideo(this.urls);\n this._loaded = true;\n if (!video) {\n return;\n }\n this.video = video;\n this.video.loop = true;\n\n // Start repainting when video starts playing. hasTransition() will then return\n // true to trigger additional frames as long as the videos continues playing.\n this.video.addEventListener('playing', () => {\n this.map.triggerRepaint();\n });\n\n if (this.map) {\n this.video.play();\n }\n\n this._finishLoading();\n } catch (err) {\n this.fire(new ErrorEvent(err));\n }\n }\n\n /**\n * Pauses the video.\n */\n pause() {\n if (this.video) {\n this.video.pause();\n }\n }\n\n /**\n * Plays the video.\n */\n play() {\n if (this.video) {\n this.video.play();\n }\n }\n\n /**\n * Sets playback to a timestamp, in seconds.\n */\n seek(seconds: number) {\n if (this.video) {\n const seekableRange = this.video.seekable;\n if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${this.id}`, null, `Playback for this video can be set only between the ${seekableRange.start(0)} and ${seekableRange.end(0)}-second mark.`)));\n } else this.video.currentTime = seconds;\n }\n }\n\n /**\n * Returns the HTML `video` element.\n *\n * @returns The HTML `video` element.\n */\n getVideo(): HTMLVideoElement {\n return this.video;\n }\n\n onAdd(map: Map) {\n if (this.map) return;\n this.map = map;\n this.load();\n if (this.video) {\n this.video.play();\n this.setCoordinates(this.coordinates);\n }\n }\n\n /**\n * Sets the video's coordinates and re-renders the map.\n */\n prepare(): this {\n if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) {\n return; // not enough data for current position\n }\n\n const context = this.map.painter.context;\n const gl = context.gl;\n\n if (!this.boundsBuffer) {\n this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);\n }\n\n if (!this.boundsSegments) {\n this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n }\n\n if (!this.texture) {\n this.texture = new Texture(context, this.video, gl.RGBA);\n this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n } else if (!this.video.paused) {\n this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video);\n }\n\n let newTilesLoaded = false;\n for (const w in this.tiles) {\n const tile = this.tiles[w];\n if (tile.state !== 'loaded') {\n tile.state = 'loaded';\n tile.texture = this.texture;\n newTilesLoaded = true;\n }\n }\n\n if (newTilesLoaded) {\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'idle', sourceId: this.id}));\n }\n }\n\n serialize(): VideoSourceSpecification {\n return {\n type: 'video',\n urls: this.urls,\n coordinates: this.coordinates\n };\n }\n\n hasTransition() {\n return this.video && !this.video.paused;\n }\n}\n","import {ImageSource} from './image_source';\n\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport {SegmentVector} from '../data/segment';\nimport {Texture} from '../render/texture';\nimport {Event, ErrorEvent} from '../util/evented';\nimport {ValidationError} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {Map} from '../ui/map';\nimport type {Dispatcher} from '../util/dispatcher';\nimport type {Evented} from '../util/evented';\n\n/**\n * Options to add a canvas source type to the map.\n */\nexport type CanvasSourceSpecification = {\n /**\n * Source type. Must be `\"canvas\"`.\n */\n type: 'canvas';\n /**\n * Four geographical coordinates denoting where to place the corners of the canvas, specified in `[longitude, latitude]` pairs.\n */\n coordinates: [[number, number], [number, number], [number, number], [number, number]];\n /**\n * Whether the canvas source is animated. If the canvas is static (i.e. pixels do not need to be re-read on every frame), `animate` should be set to `false` to improve performance.\n * @defaultValue true\n */\n animate?: boolean;\n /**\n * Canvas source from which to read pixels. Can be a string representing the ID of the canvas element, or the `HTMLCanvasElement` itself.\n */\n canvas?: string | HTMLCanvasElement;\n};\n\n/**\n * A data source containing the contents of an HTML canvas. See {@link CanvasSourceSpecification} for detailed documentation of options.\n *\n * @group Sources\n *\n * @example\n * ```ts\n * // add to map\n * map.addSource('some id', {\n * type: 'canvas',\n * canvas: 'idOfMyHTMLCanvas',\n * animate: true,\n * coordinates: [\n * [-76.54, 39.18],\n * [-76.52, 39.18],\n * [-76.52, 39.17],\n * [-76.54, 39.17]\n * ]\n * });\n *\n * // update\n * let mySource = map.getSource('some id');\n * mySource.setCoordinates([\n * [-76.54335737228394, 39.18579907229748],\n * [-76.52803659439087, 39.1838364847587],\n * [-76.5295386314392, 39.17683392507606],\n * [-76.54520273208618, 39.17876344106642]\n * ]);\n *\n * map.removeSource('some id'); // remove\n * ```\n */\nexport class CanvasSource extends ImageSource {\n options: CanvasSourceSpecification;\n animate: boolean;\n canvas: HTMLCanvasElement;\n width: number;\n height: number;\n /**\n * Enables animation. The image will be copied from the canvas to the map on each frame.\n */\n play: () => void;\n /**\n * Disables animation. The map will display a static copy of the canvas image.\n */\n pause: () => void;\n _playing: boolean;\n\n /** @internal */\n constructor(id: string, options: CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super(id, options, dispatcher, eventedParent);\n\n // We build in some validation here, since canvas sources aren't included in the style spec:\n if (!options.coordinates) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property \"coordinates\"')));\n } else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 ||\n options.coordinates.some(c => !Array.isArray(c) || c.length !== 2 || c.some(l => typeof l !== 'number'))) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '\"coordinates\" property must be an array of 4 longitude/latitude array pairs')));\n }\n\n if (options.animate && typeof options.animate !== 'boolean') {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'optional \"animate\" property must be a boolean value')));\n }\n\n if (!options.canvas) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property \"canvas\"')));\n } else if (typeof options.canvas !== 'string' && !(options.canvas instanceof HTMLCanvasElement)) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '\"canvas\" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance')));\n }\n\n this.options = options;\n this.animate = options.animate !== undefined ? options.animate : true;\n }\n\n async load() {\n this._loaded = true;\n if (!this.canvas) {\n this.canvas = (this.options.canvas instanceof HTMLCanvasElement) ?\n this.options.canvas :\n document.getElementById(this.options.canvas) as HTMLCanvasElement;\n // cast to HTMLCanvasElement in else of ternary\n // should we do a safety check and throw if it's not actually HTMLCanvasElement?\n }\n this.width = this.canvas.width;\n this.height = this.canvas.height;\n\n if (this._hasInvalidDimensions()) {\n this.fire(new ErrorEvent(new Error('Canvas dimensions cannot be less than or equal to zero.')));\n return;\n }\n\n this.play = function() {\n this._playing = true;\n this.map.triggerRepaint();\n };\n\n this.pause = function() {\n if (this._playing) {\n this.prepare();\n this._playing = false;\n }\n };\n\n this._finishLoading();\n }\n\n /**\n * Returns the HTML `canvas` element.\n *\n * @returns The HTML `canvas` element.\n */\n getCanvas(): HTMLCanvasElement {\n return this.canvas;\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n if (this.canvas) {\n if (this.animate) this.play();\n }\n }\n\n onRemove() {\n this.pause();\n }\n\n prepare() {\n let resize = false;\n if (this.canvas.width !== this.width) {\n this.width = this.canvas.width;\n resize = true;\n }\n if (this.canvas.height !== this.height) {\n this.height = this.canvas.height;\n resize = true;\n }\n\n if (this._hasInvalidDimensions()) return;\n\n if (Object.keys(this.tiles).length === 0) return; // not enough data for current position\n\n const context = this.map.painter.context;\n const gl = context.gl;\n\n if (!this.boundsBuffer) {\n this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);\n }\n\n if (!this.boundsSegments) {\n this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n }\n\n if (!this.texture) {\n this.texture = new Texture(context, this.canvas, gl.RGBA, {premultiply: true});\n } else if (resize || this._playing) {\n this.texture.update(this.canvas, {premultiply: true});\n }\n\n let newTilesLoaded = false;\n for (const w in this.tiles) {\n const tile = this.tiles[w];\n if (tile.state !== 'loaded') {\n tile.state = 'loaded';\n tile.texture = this.texture;\n newTilesLoaded = true;\n }\n }\n\n if (newTilesLoaded) {\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'idle', sourceId: this.id}));\n }\n }\n\n serialize(): CanvasSourceSpecification {\n return {\n type: 'canvas',\n coordinates: this.coordinates\n };\n }\n\n hasTransition() {\n return this._playing;\n }\n\n _hasInvalidDimensions() {\n for (const x of [this.canvas.width, this.canvas.height]) {\n if (isNaN(x) || x <= 0) return true;\n }\n return false;\n }\n}\n","import {VectorTileSource} from '../source/vector_tile_source';\nimport {RasterTileSource} from '../source/raster_tile_source';\nimport {RasterDEMTileSource} from '../source/raster_dem_tile_source';\nimport {GeoJSONSource} from '../source/geojson_source';\nimport {VideoSource} from '../source/video_source';\nimport {ImageSource} from '../source/image_source';\nimport {CanvasSource} from '../source/canvas_source';\nimport {Dispatcher} from '../util/dispatcher';\n\nimport type {SourceSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Event, Evented} from '../util/evented';\nimport type {Map} from '../ui/map';\nimport type {Tile} from './tile';\nimport type {OverscaledTileID, CanonicalTileID} from './tile_id';\nimport type {CanvasSourceSpecification} from '../source/canvas_source';\n\nconst registeredSources = {} as {[key:string]: SourceClass};\n\n/**\n * The `Source` interface must be implemented by each source type, including \"core\" types (`vector`, `raster`,\n * `video`, etc.) and all custom, third-party types.\n *\n * **Event** `data` - Fired with `{dataType: 'source', sourceDataType: 'metadata'}` to indicate that any necessary metadata\n * has been loaded so that it's okay to call `loadTile`; and with `{dataType: 'source', sourceDataType: 'content'}`\n * to indicate that the source data has changed, so that any current caches should be flushed.\n *\n * @group Sources\n */\nexport interface Source {\n readonly type: string;\n /**\n * The id for the source. Must not be used by any existing source.\n */\n id: string;\n /**\n * The minimum zoom level for the source.\n */\n minzoom: number;\n /**\n * The maximum zoom level for the source.\n */\n maxzoom: number;\n /**\n * The tile size for the source.\n */\n tileSize: number;\n /**\n * The attribution for the source.\n */\n attribution?: string;\n /**\n * `true` if zoom levels are rounded to the nearest integer in the source data, `false` if they are floor-ed to the nearest integer.\n */\n roundZoom?: boolean;\n /**\n * `false` if tiles can be drawn outside their boundaries, `true` if they cannot.\n */\n isTileClipped?: boolean;\n tileID?: CanonicalTileID;\n /**\n * `true` if tiles should be sent back to the worker for each overzoomed zoom level, `false` if not.\n */\n reparseOverscaled?: boolean;\n vectorLayerIds?: Array;\n /**\n * True if the source has transition, false otherwise.\n */\n hasTransition(): boolean;\n /**\n * True if the source is loaded, false otherwise.\n */\n loaded(): boolean;\n /**\n * An ability to fire an event to all the listeners, see {@link Evented}\n * @param event - The event to fire\n */\n fire(event: Event): unknown;\n /**\n * This method is called when the source is added to the map.\n * @param map - The map instance\n */\n onAdd?(map: Map): void;\n /**\n * This method is called when the source is removed from the map.\n * @param map - The map instance\n */\n onRemove?(map: Map): void;\n /**\n * This method does the heavy lifting of loading a tile.\n * In most cases it will defer the work to the relevant worker source.\n * @param tile - The tile to load\n */\n loadTile(tile: Tile): Promise;\n /**\n * True is the tile is part of the source, false otherwise.\n * @param tileID - The tile ID\n */\n hasTile?(tileID: OverscaledTileID): boolean;\n /**\n * Allows to abort a tile loading.\n * @param tile - The tile to abort\n */\n abortTile?(tile: Tile): Promise;\n /**\n * Allows to unload a tile.\n * @param tile - The tile to unload\n */\n unloadTile?(tile: Tile): Promise;\n /**\n * @returns A plain (stringifiable) JS object representing the current state of the source.\n * Creating a source using the returned object as the `options` should result in a Source that is\n * equivalent to this one.\n */\n serialize(): any;\n /**\n * Allows to execute a prepare step before the source is used.\n */\n prepare?(): void;\n}\n\n/**\n * A general definition of a {@link Source} class for factory usage\n */\nexport type SourceClass = {\n new (id: string, specification: SourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented): Source;\n}\n\n/**\n * Creates a tiled data source instance given an options object.\n *\n * @param id - The id for the source. Must not be used by any existing source.\n * @param specification - Source options, specific to the source type (except for `options.type`, which is always required).\n * @param source - A source definition object compliant with\n * [`maplibre-gl-style-spec`](https://maplibre.org/maplibre-style-spec/#sources) or, for a third-party source type,\n * with that type's requirements.\n * @param dispatcher - A {@link Dispatcher} instance, which can be used to send messages to the workers.\n * @returns a newly created source\n */\nexport const create = (id: string, specification: SourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented): Source => {\n\n const Class = getSourceType(specification.type);\n const source = new Class(id, specification, dispatcher, eventedParent);\n\n if (source.id !== id) {\n throw new Error(`Expected Source id to be ${id} instead of ${source.id}`);\n }\n\n return source;\n};\n\nconst getSourceType = (name: string): SourceClass => {\n switch (name) {\n case 'geojson':\n return GeoJSONSource;\n case 'image':\n return ImageSource;\n case 'raster':\n return RasterTileSource;\n case 'raster-dem':\n return RasterDEMTileSource;\n case 'vector':\n return VectorTileSource;\n case 'video':\n return VideoSource;\n case 'canvas':\n return CanvasSource;\n }\n return registeredSources[name];\n};\n\nconst setSourceType = (name: string, type: SourceClass) => {\n registeredSources[name] = type;\n};\n\n/**\n * Adds a custom source type, making it available for use with {@link Map#addSource}.\n * @param name - The name of the source type; source definition objects use this name in the `{type: ...}` field.\n * @param SourceType - A {@link SourceClass} - which is a constructor for the `Source` interface.\n * @returns a promise that is resolved when the source type is ready or rejected with an error.\n */\nexport const addSourceType = async (name: string, SourceType: SourceClass): Promise => {\n if (getSourceType(name)) {\n throw new Error(`A source type called \"${name}\" already exists.`);\n }\n setSourceType(name, SourceType);\n};\n","export class DictionaryCoder {\n _stringToNumber: {[_: string]: number};\n _numberToString: Array;\n\n constructor(strings: Array) {\n this._stringToNumber = {};\n this._numberToString = [];\n for (let i = 0; i < strings.length; i++) {\n const string = strings[i];\n this._stringToNumber[string] = i;\n this._numberToString[i] = string;\n }\n }\n\n encode(string: string) {\n return this._stringToNumber[string];\n }\n\n decode(n: number) {\n if (n >= this._numberToString.length) throw new Error(`Out of bounds. Index requested n=${n} can't be >= this._numberToString.length ${this._numberToString.length}`);\n return this._numberToString[n];\n }\n}\n","import type {VectorTileFeature} from '@mapbox/vector-tile';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * A helper for type to omit a property from a type\n */\ntype DistributiveKeys = T extends T ? keyof T : never;\n/**\n * A helper for type to omit a property from a type\n */\ntype DistributiveOmit> = T extends unknown\n ? Omit\n : never;\n\n/**\n * An extended geojson feature used by the events to return data to the listener\n */\nexport type MapGeoJSONFeature = GeoJSONFeature & {\n layer: DistributiveOmit & {source: string};\n source: string;\n sourceLayer?: string;\n state: { [key: string]: any };\n}\n\n/**\n * A geojson feature\n */\nexport class GeoJSONFeature {\n type: 'Feature';\n _geometry: GeoJSON.Geometry;\n properties: { [name: string]: any };\n id: number | string | undefined;\n\n _vectorTileFeature: VectorTileFeature;\n\n constructor(vectorTileFeature: VectorTileFeature, z: number, x: number, y: number, id: string | number | undefined) {\n this.type = 'Feature';\n\n this._vectorTileFeature = vectorTileFeature;\n (vectorTileFeature as any)._z = z;\n (vectorTileFeature as any)._x = x;\n (vectorTileFeature as any)._y = y;\n\n this.properties = vectorTileFeature.properties;\n this.id = id;\n }\n\n get geometry(): GeoJSON.Geometry {\n if (this._geometry === undefined) {\n this._geometry = this._vectorTileFeature.toGeoJSON(\n (this._vectorTileFeature as any)._x,\n (this._vectorTileFeature as any)._y,\n (this._vectorTileFeature as any)._z).geometry;\n }\n return this._geometry;\n }\n\n set geometry(g: GeoJSON.Geometry) {\n this._geometry = g;\n }\n\n toJSON() {\n const json: any = {\n geometry: this.geometry\n };\n for (const i in this) {\n if (i === '_geometry' || i === '_vectorTileFeature') continue;\n json[i] = (this)[i];\n }\n return json;\n }\n}\n","import Point from '@mapbox/point-geometry';\nimport {loadGeometry} from './load_geometry';\nimport {toEvaluationFeature} from './evaluation_feature';\nimport {EXTENT} from './extent';\nimport {featureFilter} from '@maplibre/maplibre-gl-style-spec';\nimport {TransferableGridIndex} from '../util/transferable_grid_index';\nimport {DictionaryCoder} from '../util/dictionary_coder';\nimport vt from '@mapbox/vector-tile';\nimport Protobuf from 'pbf';\nimport {GeoJSONFeature} from '../util/vectortile_to_geojson';\nimport type {MapGeoJSONFeature} from '../util/vectortile_to_geojson';\nimport {arraysIntersect, mapObject, extend} from '../util/util';\nimport {OverscaledTileID} from '../source/tile_id';\nimport {register} from '../util/web_worker_transfer';\nimport {EvaluationParameters} from '../style/evaluation_parameters';\nimport {SourceFeatureState} from '../source/source_state';\nimport {polygonIntersectsBox} from '../util/intersection_tests';\nimport {PossiblyEvaluated} from '../style/properties';\nimport {FeatureIndexArray} from './array_types.g';\nimport {mat4} from 'gl-matrix';\n\nimport type {StyleLayer} from '../style/style_layer';\nimport type {FeatureFilter, FeatureState, FilterSpecification, PromoteIdSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Transform} from '../geo/transform';\nimport type {VectorTileFeature, VectorTileLayer} from '@mapbox/vector-tile';\n\ntype QueryParameters = {\n scale: number;\n pixelPosMatrix: mat4;\n transform: Transform;\n tileSize: number;\n queryGeometry: Array;\n cameraQueryGeometry: Array;\n queryPadding: number;\n params: {\n filter: FilterSpecification;\n layers: Array;\n availableImages: Array;\n };\n};\n\n/**\n * An in memory index class to allow fast interaction with features\n */\nexport class FeatureIndex {\n tileID: OverscaledTileID;\n x: number;\n y: number;\n z: number;\n grid: TransferableGridIndex;\n grid3D: TransferableGridIndex;\n featureIndexArray: FeatureIndexArray;\n promoteId?: PromoteIdSpecification;\n\n rawTileData: ArrayBuffer;\n bucketLayerIDs: Array>;\n\n vtLayers: {[_: string]: VectorTileLayer};\n sourceLayerCoder: DictionaryCoder;\n\n constructor(tileID: OverscaledTileID, promoteId?: PromoteIdSpecification | null) {\n this.tileID = tileID;\n this.x = tileID.canonical.x;\n this.y = tileID.canonical.y;\n this.z = tileID.canonical.z;\n this.grid = new TransferableGridIndex(EXTENT, 16, 0);\n this.grid3D = new TransferableGridIndex(EXTENT, 16, 0);\n this.featureIndexArray = new FeatureIndexArray();\n this.promoteId = promoteId;\n }\n\n insert(feature: VectorTileFeature, geometry: Array>, featureIndex: number, sourceLayerIndex: number, bucketIndex: number, is3D?: boolean) {\n const key = this.featureIndexArray.length;\n this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex);\n\n const grid = is3D ? this.grid3D : this.grid;\n\n for (let r = 0; r < geometry.length; r++) {\n const ring = geometry[r];\n\n const bbox = [Infinity, Infinity, -Infinity, -Infinity];\n for (let i = 0; i < ring.length; i++) {\n const p = ring[i];\n bbox[0] = Math.min(bbox[0], p.x);\n bbox[1] = Math.min(bbox[1], p.y);\n bbox[2] = Math.max(bbox[2], p.x);\n bbox[3] = Math.max(bbox[3], p.y);\n }\n\n if (bbox[0] < EXTENT &&\n bbox[1] < EXTENT &&\n bbox[2] >= 0 &&\n bbox[3] >= 0) {\n grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]);\n }\n }\n }\n\n loadVTLayers(): {[_: string]: VectorTileLayer} {\n if (!this.vtLayers) {\n this.vtLayers = new vt.VectorTile(new Protobuf(this.rawTileData)).layers;\n this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']);\n }\n return this.vtLayers;\n }\n\n // Finds non-symbol features in this tile at a particular position.\n query(\n args: QueryParameters,\n styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: any},\n sourceFeatureState: SourceFeatureState\n ): {[_: string]: Array<{featureIndex: number; feature: GeoJSONFeature}>} {\n this.loadVTLayers();\n\n const params = args.params || {} as { filter: any; layers: string[]; availableImages: string[] },\n pixelsToTileUnits = EXTENT / args.tileSize / args.scale,\n filter = featureFilter(params.filter);\n\n const queryGeometry = args.queryGeometry;\n const queryPadding = args.queryPadding * pixelsToTileUnits;\n\n const bounds = getBounds(queryGeometry);\n const matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding);\n\n const cameraBounds = getBounds(args.cameraQueryGeometry);\n const matching3D = this.grid3D.query(\n cameraBounds.minX - queryPadding, cameraBounds.minY - queryPadding, cameraBounds.maxX + queryPadding, cameraBounds.maxY + queryPadding,\n (bx1, by1, bx2, by2) => {\n return polygonIntersectsBox(args.cameraQueryGeometry, bx1 - queryPadding, by1 - queryPadding, bx2 + queryPadding, by2 + queryPadding);\n });\n\n for (const key of matching3D) {\n matching.push(key);\n }\n\n matching.sort(topDownFeatureComparator);\n\n const result = {};\n let previousIndex;\n for (let k = 0; k < matching.length; k++) {\n const index = matching[k];\n\n // don't check the same feature more than once\n if (index === previousIndex) continue;\n previousIndex = index;\n\n const match = this.featureIndexArray.get(index);\n let featureGeometry = null;\n this.loadMatchingFeature(\n result,\n match.bucketIndex,\n match.sourceLayerIndex,\n match.featureIndex,\n filter,\n params.layers,\n params.availableImages,\n styleLayers,\n serializedLayers,\n sourceFeatureState,\n (feature: VectorTileFeature, styleLayer: StyleLayer, featureState: FeatureState) => {\n if (!featureGeometry) {\n featureGeometry = loadGeometry(feature);\n }\n\n return styleLayer.queryIntersectsFeature(queryGeometry, feature, featureState, featureGeometry, this.z, args.transform, pixelsToTileUnits, args.pixelPosMatrix);\n }\n );\n }\n\n return result;\n }\n\n loadMatchingFeature(\n result: {\n [_: string]: Array<{\n featureIndex: number;\n feature: GeoJSONFeature;\n intersectionZ?: boolean | number;\n }>;\n },\n bucketIndex: number,\n sourceLayerIndex: number,\n featureIndex: number,\n filter: FeatureFilter,\n filterLayerIDs: Array,\n availableImages: Array,\n styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: any},\n sourceFeatureState?: SourceFeatureState,\n intersectionTest?: (\n feature: VectorTileFeature,\n styleLayer: StyleLayer,\n featureState: any,\n id: string | number | void\n ) => boolean | number) {\n\n const layerIDs = this.bucketLayerIDs[bucketIndex];\n if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs))\n return;\n\n const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex);\n const sourceLayer = this.vtLayers[sourceLayerName];\n const feature = sourceLayer.feature(featureIndex);\n\n if (filter.needGeometry) {\n const evaluationFeature = toEvaluationFeature(feature, true);\n if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) {\n return;\n }\n } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {\n return;\n }\n\n const id = this.getId(feature, sourceLayerName);\n\n for (let l = 0; l < layerIDs.length; l++) {\n const layerID = layerIDs[l];\n\n if (filterLayerIDs && filterLayerIDs.indexOf(layerID) < 0) {\n continue;\n }\n\n const styleLayer = styleLayers[layerID];\n\n if (!styleLayer) continue;\n\n let featureState = {};\n if (id && sourceFeatureState) {\n // `feature-state` expression evaluation requires feature state to be available\n featureState = sourceFeatureState.getState(styleLayer.sourceLayer || '_geojsonTileLayer', id);\n }\n\n const serializedLayer = extend({}, serializedLayers[layerID]);\n\n serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages);\n serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages);\n\n const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState);\n if (!intersectionZ) {\n // Only applied for non-symbol features\n continue;\n }\n\n const geojsonFeature = new GeoJSONFeature(feature, this.z, this.x, this.y, id) as MapGeoJSONFeature;\n geojsonFeature.layer = serializedLayer;\n let layerResult = result[layerID];\n if (layerResult === undefined) {\n layerResult = result[layerID] = [];\n }\n layerResult.push({featureIndex, feature: geojsonFeature, intersectionZ});\n }\n }\n\n // Given a set of symbol indexes that have already been looked up,\n // return a matching set of GeoJSONFeatures\n lookupSymbolFeatures(symbolFeatureIndexes: Array,\n serializedLayers: {[_: string]: StyleLayer},\n bucketIndex: number,\n sourceLayerIndex: number,\n filterSpec: FilterSpecification,\n filterLayerIDs: Array,\n availableImages: Array,\n styleLayers: {[_: string]: StyleLayer}) {\n const result = {};\n this.loadVTLayers();\n\n const filter = featureFilter(filterSpec);\n\n for (const symbolFeatureIndex of symbolFeatureIndexes) {\n this.loadMatchingFeature(\n result,\n bucketIndex,\n sourceLayerIndex,\n symbolFeatureIndex,\n filter,\n filterLayerIDs,\n availableImages,\n styleLayers,\n serializedLayers\n );\n\n }\n return result;\n }\n\n hasLayer(id: string) {\n for (const layerIDs of this.bucketLayerIDs) {\n for (const layerID of layerIDs) {\n if (id === layerID) return true;\n }\n }\n\n return false;\n }\n\n getId(feature: VectorTileFeature, sourceLayerId: string): string | number {\n let id: string | number = feature.id;\n if (this.promoteId) {\n const propName = typeof this.promoteId === 'string' ? this.promoteId : this.promoteId[sourceLayerId];\n id = feature.properties[propName] as string | number;\n if (typeof id === 'boolean') id = Number(id);\n }\n return id;\n }\n}\n\nregister(\n 'FeatureIndex',\n FeatureIndex,\n {omit: ['rawTileData', 'sourceLayerCoder']}\n);\n\nfunction evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) {\n return mapObject(serializedProperties, (property, key) => {\n const prop = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null;\n return prop && prop.evaluate ? prop.evaluate(feature, featureState, availableImages) : prop;\n });\n}\n\nfunction getBounds(geometry: Array) {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const p of geometry) {\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x);\n maxY = Math.max(maxY, p.y);\n }\n return {minX, minY, maxX, maxY};\n}\n\nfunction topDownFeatureComparator(a, b) {\n return b - a;\n}\n","/**\n * The possible option of the plugin's status\n *\n * `unavailable`: Not loaded.\n *\n * `deferred`: The plugin URL has been specified, but loading has been deferred.\n *\n * `requested`: at least one tile needs RTL to render, but the plugin has not been set\n *\n * `loading`: RTL is in the process of being loaded by worker.\n *\n * `loaded`: The plugin is now loaded\n *\n * `error`: The plugin failed to load\n */\nexport type RTLPluginStatus =\n 'unavailable' |\n 'deferred' |\n 'requested' |\n 'loading' |\n 'loaded' |\n 'error';\n\n/**\n * The RTL plugin state\n */\nexport type PluginState = {\n pluginStatus: RTLPluginStatus;\n pluginURL: string;\n};\n\nexport const RTLPluginLoadedEventName = 'RTLPluginLoaded';\n\n","\nimport {browser} from '../util/browser';\nimport {Event, Evented} from '../util/evented';\nimport {RTLPluginStatus, RTLPluginLoadedEventName, PluginState} from './rtl_text_plugin_status';\nimport {Dispatcher, getGlobalDispatcher} from '../util/dispatcher';\nimport {MessageType} from '../util/actor_messages';\n\nclass RTLMainThreadPlugin extends Evented {\n status: RTLPluginStatus = 'unavailable';\n url: string = null;\n dispatcher: Dispatcher = getGlobalDispatcher();\n\n /** Sync RTL plugin state by broadcasting a message to the worker */\n _syncState(statusToSend: RTLPluginStatus): Promise {\n this.status = statusToSend;\n return this.dispatcher.broadcast(MessageType.syncRTLPluginState, {pluginStatus: statusToSend, pluginURL: this.url})\n .catch((e: any) => {\n this.status = 'error';\n throw e;\n });\n }\n\n /** This one is exposed to outside */\n getRTLTextPluginStatus(): RTLPluginStatus {\n return this.status;\n }\n\n clearRTLTextPlugin(): void {\n this.status = 'unavailable';\n this.url = null;\n }\n\n async setRTLTextPlugin(url: string, deferred: boolean = false): Promise {\n if (this.url) {\n // error\n throw new Error('setRTLTextPlugin cannot be called multiple times.');\n }\n\n this.url = browser.resolveURL(url);\n if (!this.url) {\n throw new Error(`requested url ${url} is invalid`);\n }\n if (this.status === 'unavailable') {\n\n // from initial state:\n if (deferred) {\n\n this.status = 'deferred';\n // fire and forget: in this case it does not need wait for the broadcasting result\n // it is important to sync the deferred status once because\n // symbol_bucket will be checking it in worker\n this._syncState(this.status);\n\n } else {\n return this._requestImport();\n }\n\n } else if (this.status === 'requested') {\n return this._requestImport();\n }\n }\n\n /** Send a message to worker which will import the RTL plugin script */\n async _requestImport() : Promise {\n\n // all errors/exceptions will be handled by _syncState\n await this._syncState('loading');\n this.status = 'loaded';\n this.fire(new Event(RTLPluginLoadedEventName));\n }\n\n /** Start a lazy loading process of RTL plugin */\n lazyLoad(): void {\n if (this.status === 'unavailable') {\n this.status = 'requested';\n } else if (this.status === 'deferred') {\n this._requestImport();\n }\n }\n}\n\nlet rtlMainThreadPlugin: RTLMainThreadPlugin = null;\n\nexport function rtlMainThreadPluginFactory(): RTLMainThreadPlugin {\n if (!rtlMainThreadPlugin) {\n rtlMainThreadPlugin = new RTLMainThreadPlugin();\n }\n return rtlMainThreadPlugin;\n}\n","import {uniqueId, parseCacheControl} from '../util/util';\nimport {deserialize as deserializeBucket} from '../data/bucket';\nimport '../data/feature_index';\nimport type {FeatureIndex} from '../data/feature_index';\nimport {GeoJSONFeature} from '../util/vectortile_to_geojson';\nimport {featureFilter} from '@maplibre/maplibre-gl-style-spec';\nimport {SymbolBucket} from '../data/bucket/symbol_bucket';\nimport {CollisionBoxArray} from '../data/array_types.g';\nimport {Texture} from '../render/texture';\nimport {browser} from '../util/browser';\nimport {toEvaluationFeature} from '../data/evaluation_feature';\nimport {EvaluationParameters} from '../style/evaluation_parameters';\nimport {SourceFeatureState} from '../source/source_state';\nimport {rtlMainThreadPluginFactory} from './rtl_text_plugin_main_thread';\n\nconst CLOCK_SKEW_RETRY_TIMEOUT = 30000;\n\nimport type {Bucket} from '../data/bucket';\nimport type {StyleLayer} from '../style/style_layer';\nimport type {WorkerTileResult} from './worker_source';\nimport type {Actor} from '../util/actor';\nimport type {DEMData} from '../data/dem_data';\nimport type {AlphaImage} from '../util/image';\nimport type {ImageAtlas} from '../render/image_atlas';\nimport type {ImageManager} from '../render/image_manager';\nimport type {Context} from '../gl/context';\nimport type {OverscaledTileID} from './tile_id';\nimport type {Framebuffer} from '../gl/framebuffer';\nimport type {Transform} from '../geo/transform';\nimport type {LayerFeatureStates} from './source_state';\nimport type {FilterSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type Point from '@mapbox/point-geometry';\nimport {mat4} from 'gl-matrix';\nimport type {VectorTileLayer} from '@mapbox/vector-tile';\nimport {ExpiryData} from '../util/ajax';\n\n/**\n * The tile's state, can be:\n *\n * - `loading` Tile data is in the process of loading.\n * - `loaded` Tile data has been loaded. Tile can be rendered.\n * - `reloading` Tile data has been loaded and is being updated. Tile can be rendered.\n * - `unloaded` Tile data has been deleted.\n * - `errored` Tile data was not loaded because of an error.\n * - `expired` Tile data was previously loaded, but has expired per its HTTP headers and is in the process of refreshing.\n */\nexport type TileState = 'loading' | 'loaded' | 'reloading' | 'unloaded' | 'errored' | 'expired';\n\n/**\n * A tile object is the combination of a Coordinate, which defines\n * its place, as well as a unique ID and data tracking for its content\n */\nexport class Tile {\n tileID: OverscaledTileID;\n uid: number;\n uses: number;\n tileSize: number;\n buckets: {[_: string]: Bucket};\n latestFeatureIndex: FeatureIndex;\n latestRawTileData: ArrayBuffer;\n imageAtlas: ImageAtlas;\n imageAtlasTexture: Texture;\n glyphAtlasImage: AlphaImage;\n glyphAtlasTexture: Texture;\n expirationTime: any;\n expiredRequestCount: number;\n state: TileState;\n timeAdded: number = 0;\n fadeEndTime: number = 0;\n collisionBoxArray: CollisionBoxArray;\n redoWhenDone: boolean;\n showCollisionBoxes: boolean;\n placementSource: any;\n actor: Actor;\n vtLayers: {[_: string]: VectorTileLayer};\n\n neighboringTiles: any;\n dem: DEMData;\n demMatrix: mat4;\n aborted: boolean;\n needsHillshadePrepare: boolean;\n needsTerrainPrepare: boolean;\n abortController: AbortController;\n texture: any;\n fbo: Framebuffer;\n demTexture: Texture;\n refreshedUponExpiration: boolean;\n reloadPromise: {resolve: () => void; reject: () => void};\n resourceTiming: Array;\n queryPadding: number;\n\n symbolFadeHoldUntil: number;\n hasSymbolBuckets: boolean;\n hasRTLText: boolean;\n dependencies: any;\n rtt: Array<{id: number; stamp: number}>;\n rttCoords: {[_:string]: string};\n\n /**\n * @param tileID - the tile ID\n * @param size - The tile size\n */\n constructor(tileID: OverscaledTileID, size: number) {\n this.tileID = tileID;\n this.uid = uniqueId();\n this.uses = 0;\n this.tileSize = size;\n this.buckets = {};\n this.expirationTime = null;\n this.queryPadding = 0;\n this.hasSymbolBuckets = false;\n this.hasRTLText = false;\n this.dependencies = {};\n this.rtt = [];\n this.rttCoords = {};\n\n // Counts the number of times a response was already expired when\n // received. We're using this to add a delay when making a new request\n // so we don't have to keep retrying immediately in case of a server\n // serving expired tiles.\n this.expiredRequestCount = 0;\n\n this.state = 'loading';\n }\n\n registerFadeDuration(duration: number) {\n const fadeEndTime = duration + this.timeAdded;\n\n if (fadeEndTime < this.fadeEndTime) {\n return;\n }\n\n this.fadeEndTime = fadeEndTime;\n }\n\n wasRequested() {\n return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading';\n }\n\n clearTextures(painter: any) {\n if (this.demTexture) painter.saveTileTexture(this.demTexture);\n this.demTexture = null;\n }\n\n /**\n * Given a data object with a 'buffers' property, load it into\n * this tile's elementGroups and buffers properties and set loaded\n * to true. If the data is null, like in the case of an empty\n * GeoJSON tile, no-op but still set loaded to true.\n * @param data - The data from the worker\n * @param painter - the painter\n * @param justReloaded - `true` to just reload\n */\n loadVectorData(data: WorkerTileResult, painter: any, justReloaded?: boolean | null) {\n if (this.hasData()) {\n this.unloadVectorData();\n }\n\n this.state = 'loaded';\n\n // empty GeoJSON tile\n if (!data) {\n this.collisionBoxArray = new CollisionBoxArray();\n return;\n }\n\n if (data.featureIndex) {\n this.latestFeatureIndex = data.featureIndex;\n if (data.rawTileData) {\n // Only vector tiles have rawTileData, and they won't update it for\n // 'reloadTile'\n this.latestRawTileData = data.rawTileData;\n this.latestFeatureIndex.rawTileData = data.rawTileData;\n } else if (this.latestRawTileData) {\n // If rawTileData hasn't updated, hold onto a pointer to the last\n // one we received\n this.latestFeatureIndex.rawTileData = this.latestRawTileData;\n }\n }\n this.collisionBoxArray = data.collisionBoxArray;\n this.buckets = deserializeBucket(data.buckets, painter.style);\n\n this.hasSymbolBuckets = false;\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n if (bucket instanceof SymbolBucket) {\n this.hasSymbolBuckets = true;\n if (justReloaded) {\n bucket.justReloaded = true;\n } else {\n break;\n }\n }\n }\n\n this.hasRTLText = false;\n if (this.hasSymbolBuckets) {\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n if (bucket instanceof SymbolBucket) {\n if (bucket.hasRTLText) {\n this.hasRTLText = true;\n rtlMainThreadPluginFactory().lazyLoad();\n break;\n }\n }\n }\n }\n\n this.queryPadding = 0;\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket));\n }\n\n if (data.imageAtlas) {\n this.imageAtlas = data.imageAtlas;\n }\n if (data.glyphAtlasImage) {\n this.glyphAtlasImage = data.glyphAtlasImage;\n }\n }\n\n /**\n * Release any data or WebGL resources referenced by this tile.\n */\n unloadVectorData() {\n for (const id in this.buckets) {\n this.buckets[id].destroy();\n }\n this.buckets = {};\n\n if (this.imageAtlasTexture) {\n this.imageAtlasTexture.destroy();\n }\n\n if (this.imageAtlas) {\n this.imageAtlas = null;\n }\n\n if (this.glyphAtlasTexture) {\n this.glyphAtlasTexture.destroy();\n }\n\n this.latestFeatureIndex = null;\n this.state = 'unloaded';\n }\n\n getBucket(layer: StyleLayer) {\n return this.buckets[layer.id];\n }\n\n upload(context: Context) {\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n if (bucket.uploadPending()) {\n bucket.upload(context);\n }\n }\n\n const gl = context.gl;\n if (this.imageAtlas && !this.imageAtlas.uploaded) {\n this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA);\n this.imageAtlas.uploaded = true;\n }\n\n if (this.glyphAtlasImage) {\n this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA);\n this.glyphAtlasImage = null;\n }\n }\n\n prepare(imageManager: ImageManager) {\n if (this.imageAtlas) {\n this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture);\n }\n }\n\n // Queries non-symbol features rendered for this tile.\n // Symbol features are queried globally\n queryRenderedFeatures(\n layers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: any},\n sourceFeatureState: SourceFeatureState,\n queryGeometry: Array,\n cameraQueryGeometry: Array,\n scale: number,\n params: {\n filter: FilterSpecification;\n layers: Array;\n availableImages: Array;\n },\n transform: Transform,\n maxPitchScaleFactor: number,\n pixelPosMatrix: mat4\n ): {[_: string]: Array<{featureIndex: number; feature: GeoJSONFeature}>} {\n if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData)\n return {};\n\n return this.latestFeatureIndex.query({\n queryGeometry,\n cameraQueryGeometry,\n scale,\n tileSize: this.tileSize,\n pixelPosMatrix,\n transform,\n params,\n queryPadding: this.queryPadding * maxPitchScaleFactor\n }, layers, serializedLayers, sourceFeatureState);\n }\n\n querySourceFeatures(result: Array, params?: {\n sourceLayer?: string;\n filter?: FilterSpecification;\n validate?: boolean;\n }) {\n const featureIndex = this.latestFeatureIndex;\n if (!featureIndex || !featureIndex.rawTileData) return;\n\n const vtLayers = featureIndex.loadVTLayers();\n\n const sourceLayer = params && params.sourceLayer ? params.sourceLayer : '';\n const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer];\n\n if (!layer) return;\n\n const filter = featureFilter(params && params.filter);\n const {z, x, y} = this.tileID.canonical;\n const coord = {z, x, y};\n\n for (let i = 0; i < layer.length; i++) {\n const feature = layer.feature(i);\n if (filter.needGeometry) {\n const evaluationFeature = toEvaluationFeature(feature, true);\n if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) continue;\n } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {\n continue;\n }\n const id = featureIndex.getId(feature, sourceLayer);\n const geojsonFeature = new GeoJSONFeature(feature, z, x, y, id);\n (geojsonFeature as any).tile = coord;\n result.push(geojsonFeature);\n }\n }\n\n hasData() {\n return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired';\n }\n\n patternsLoaded() {\n return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;\n }\n\n setExpiryData(data: ExpiryData) {\n const prior = this.expirationTime;\n\n if (data.cacheControl) {\n const parsedCC = parseCacheControl(data.cacheControl);\n if (parsedCC['max-age']) this.expirationTime = Date.now() + parsedCC['max-age'] * 1000;\n } else if (data.expires) {\n this.expirationTime = new Date(data.expires).getTime();\n }\n\n if (this.expirationTime) {\n const now = Date.now();\n let isExpired = false;\n\n if (this.expirationTime > now) {\n isExpired = false;\n } else if (!prior) {\n isExpired = true;\n } else if (this.expirationTime < prior) {\n // Expiring date is going backwards:\n // fall back to exponential backoff\n isExpired = true;\n\n } else {\n const delta = this.expirationTime - prior;\n\n if (!delta) {\n // Server is serving the same expired resource over and over: fall\n // back to exponential backoff.\n isExpired = true;\n\n } else {\n // Assume that either the client or the server clock is wrong and\n // try to interpolate a valid expiration date (from the client POV)\n // observing a minimum timeout.\n this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT);\n\n }\n }\n\n if (isExpired) {\n this.expiredRequestCount++;\n this.state = 'expired';\n } else {\n this.expiredRequestCount = 0;\n }\n }\n }\n\n getExpiryTimeout() {\n if (this.expirationTime) {\n if (this.expiredRequestCount) {\n return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31));\n } else {\n // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly\n return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1);\n }\n }\n }\n\n setFeatureState(states: LayerFeatureStates, painter: any) {\n if (!this.latestFeatureIndex ||\n !this.latestFeatureIndex.rawTileData ||\n Object.keys(states).length === 0) {\n return;\n }\n\n const vtLayers = this.latestFeatureIndex.loadVTLayers();\n\n for (const id in this.buckets) {\n if (!painter.style.hasLayer(id)) continue;\n\n const bucket = this.buckets[id];\n // Buckets are grouped by common source-layer\n const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer';\n const sourceLayer = vtLayers[sourceLayerId];\n const sourceLayerStates = states[sourceLayerId];\n if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) continue;\n\n bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas && this.imageAtlas.patternPositions || {});\n const layer = painter && painter.style && painter.style.getLayer(id);\n if (layer) {\n this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket));\n }\n }\n }\n\n holdingForFade(): boolean {\n return this.symbolFadeHoldUntil !== undefined;\n }\n\n symbolFadeFinished(): boolean {\n return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < browser.now();\n }\n\n clearFadeHold() {\n this.symbolFadeHoldUntil = undefined;\n }\n\n setHoldDuration(duration: number) {\n this.symbolFadeHoldUntil = browser.now() + duration;\n }\n\n setDependencies(namespace: string, dependencies: Array) {\n const index = {};\n for (const dep of dependencies) {\n index[dep] = true;\n }\n this.dependencies[namespace] = index;\n }\n\n hasDependency(namespaces: Array, keys: Array) {\n for (const namespace of namespaces) {\n const dependencies = this.dependencies[namespace];\n if (dependencies) {\n for (const key of keys) {\n if (dependencies[key]) {\n return true;\n }\n }\n }\n }\n return false;\n }\n}\n","import type {CollisionBoxArray} from './array_types.g';\nimport type {Style} from '../style/style';\nimport type {TypedStyleLayer} from '../style/style_layer/typed_style_layer';\nimport type {FeatureIndex} from './feature_index';\nimport type {Context} from '../gl/context';\nimport type {FeatureStates} from '../source/source_state';\nimport type {ImagePosition} from '../render/image_atlas';\nimport type {CanonicalTileID} from '../source/tile_id';\nimport type {VectorTileFeature, VectorTileLayer} from '@mapbox/vector-tile';\nimport Point from '@mapbox/point-geometry';\n\nexport type BucketParameters = {\n index: number;\n layers: Array;\n zoom: number;\n pixelRatio: number;\n overscaling: number;\n collisionBoxArray: CollisionBoxArray;\n sourceLayerIndex: number;\n sourceID: string;\n};\n\nexport type PopulateParameters = {\n featureIndex: FeatureIndex;\n iconDependencies: {};\n patternDependencies: {};\n glyphDependencies: {};\n availableImages: Array;\n};\n\nexport type IndexedFeature = {\n feature: VectorTileFeature;\n id: number | string;\n index: number;\n sourceLayerIndex: number;\n};\n\nexport type BucketFeature = {\n index: number;\n sourceLayerIndex: number;\n geometry: Array>;\n properties: any;\n type: 0 | 1 | 2 | 3;\n id?: any;\n readonly patterns: {\n [_: string]: {\n 'min': string;\n 'mid': string;\n 'max': string;\n };\n };\n sortKey?: number;\n};\n\n/**\n * The `Bucket` interface is the single point of knowledge about turning vector\n * tiles into WebGL buffers.\n *\n * `Bucket` is an abstract interface. An implementation exists for each style layer type.\n * Create a bucket via the `StyleLayer#createBucket` method.\n *\n * The concrete bucket types, using layout options from the style layer,\n * transform feature geometries into vertex and index data for use by the\n * vertex shader. They also (via `ProgramConfiguration`) use feature\n * properties and the zoom level to populate the attributes needed for\n * data-driven styling.\n *\n * Buckets are designed to be built on a worker thread and then serialized and\n * transferred back to the main thread for rendering. On the worker side, a\n * bucket's vertex, index, and attribute data is stored in `bucket.arrays: ArrayGroup`.\n * When a bucket's data is serialized and sent back to the main thread,\n * is gets deserialized (using `new Bucket(serializedBucketData)`, with\n * the array data now stored in `bucket.buffers: BufferGroup`. BufferGroups\n * hold the same data as ArrayGroups, but are tuned for consumption by WebGL.\n */\nexport interface Bucket {\n layerIds: Array;\n hasPattern: boolean;\n readonly layers: Array;\n readonly stateDependentLayers: Array;\n readonly stateDependentLayerIds: Array;\n populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID): void;\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}): void;\n isEmpty(): boolean;\n upload(context: Context): void;\n uploadPending(): boolean;\n /**\n * Release the WebGL resources associated with the buffers. Note that because\n * buckets are shared between layers having the same layout properties, they\n * must be destroyed in groups (all buckets for a tile, or all symbol buckets).\n */\n destroy(): void;\n}\n\nexport function deserialize(input: Array, style: Style): {[_: string]: Bucket} {\n const output = {};\n\n // Guard against the case where the map's style has been set to null while\n // this bucket has been parsing.\n if (!style) return output;\n\n for (const bucket of input) {\n const layers = bucket.layerIds\n .map((id) => style.getLayer(id))\n .filter(Boolean);\n\n if (layers.length === 0) {\n continue;\n }\n\n // look up StyleLayer objects from layer ids (since we don't\n // want to waste time serializing/copying them from the worker)\n (bucket as any).layers = layers;\n if (bucket.stateDependentLayerIds) {\n (bucket as any).stateDependentLayers = bucket.stateDependentLayerIds.map((lId) => layers.filter((l) => l.id === lId)[0]);\n }\n for (const layer of layers) {\n output[layer.id] = bucket;\n }\n }\n\n return output;\n}\n","import {OverscaledTileID} from './tile_id';\nimport type {Tile} from './tile';\n\n/**\n * @internal\n * A [least-recently-used cache](https://en.wikipedia.org/wiki/Cache_algorithms)\n * with hash lookup made possible by keeping a list of keys in parallel to\n * an array of dictionary of values\n */\nexport class TileCache {\n max: number;\n data: {\n [key: string]: Array<{\n value: Tile;\n timeout: ReturnType;\n }>;\n };\n order: Array;\n onRemove: (element: Tile) => void;\n /**\n * @param max - number of permitted values\n * @param onRemove - callback called with items when they expire\n */\n constructor(max: number, onRemove: (element: Tile) => void) {\n this.max = max;\n this.onRemove = onRemove;\n this.reset();\n }\n\n /**\n * Clear the cache\n *\n * @returns this cache\n */\n reset() {\n for (const key in this.data) {\n for (const removedData of this.data[key]) {\n if (removedData.timeout) clearTimeout(removedData.timeout);\n this.onRemove(removedData.value);\n }\n }\n\n this.data = {};\n this.order = [];\n\n return this;\n }\n\n /**\n * Add a key, value combination to the cache, trimming its size if this pushes\n * it over max length.\n *\n * @param tileID - lookup key for the item\n * @param data - tile data\n *\n * @returns this cache\n */\n add(tileID: OverscaledTileID, data: Tile, expiryTimeout: number | void) {\n const key = tileID.wrapped().key;\n if (this.data[key] === undefined) {\n this.data[key] = [];\n }\n\n const dataWrapper = {\n value: data,\n timeout: undefined\n };\n\n if (expiryTimeout !== undefined) {\n dataWrapper.timeout = setTimeout(() => {\n this.remove(tileID, dataWrapper);\n }, expiryTimeout as number);\n }\n\n this.data[key].push(dataWrapper);\n this.order.push(key);\n\n if (this.order.length > this.max) {\n const removedData = this._getAndRemoveByKey(this.order[0]);\n if (removedData) this.onRemove(removedData);\n }\n\n return this;\n }\n\n /**\n * Determine whether the value attached to `key` is present\n *\n * @param tileID - the key to be looked-up\n * @returns whether the cache has this value\n */\n has(tileID: OverscaledTileID): boolean {\n return tileID.wrapped().key in this.data;\n }\n\n /**\n * Get the value attached to a specific key and remove data from cache.\n * If the key is not found, returns `null`\n *\n * @param tileID - the key to look up\n * @returns the tile data, or null if it isn't found\n */\n getAndRemove(tileID: OverscaledTileID): Tile {\n if (!this.has(tileID)) { return null; }\n return this._getAndRemoveByKey(tileID.wrapped().key);\n }\n\n /*\n * Get and remove the value with the specified key.\n */\n _getAndRemoveByKey(key: string): Tile {\n const data = this.data[key].shift();\n if (data.timeout) clearTimeout(data.timeout);\n\n if (this.data[key].length === 0) {\n delete this.data[key];\n }\n this.order.splice(this.order.indexOf(key), 1);\n\n return data.value;\n }\n\n /*\n * Get the value with the specified (wrapped tile) key.\n */\n getByKey(key: string): Tile {\n const data = this.data[key];\n return data ? data[0].value : null;\n }\n\n /**\n * Get the value attached to a specific key without removing data\n * from the cache. If the key is not found, returns `null`\n *\n * @param tileID - the key to look up\n * @returns the tile data, or null if it isn't found\n */\n get(tileID: OverscaledTileID): Tile {\n if (!this.has(tileID)) { return null; }\n\n const data = this.data[tileID.wrapped().key][0];\n return data.value;\n }\n\n /**\n * Remove a key/value combination from the cache.\n *\n * @param tileID - the key for the pair to delete\n * @param value - If a value is provided, remove that exact version of the value.\n * @returns this cache\n */\n remove(tileID: OverscaledTileID, value?: {\n value: Tile;\n timeout: ReturnType;\n }) {\n if (!this.has(tileID)) { return this; }\n const key = tileID.wrapped().key;\n\n const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value);\n const data = this.data[key][dataIndex];\n this.data[key].splice(dataIndex, 1);\n if (data.timeout) clearTimeout(data.timeout);\n if (this.data[key].length === 0) {\n delete this.data[key];\n }\n this.onRemove(data.value);\n this.order.splice(this.order.indexOf(key), 1);\n\n return this;\n }\n\n /**\n * Change the max size of the cache.\n *\n * @param max - the max size of the cache\n * @returns this cache\n */\n setMaxSize(max: number): TileCache {\n this.max = max;\n\n while (this.order.length > this.max) {\n const removedData = this._getAndRemoveByKey(this.order[0]);\n if (removedData) this.onRemove(removedData);\n }\n\n return this;\n }\n\n /**\n * Remove entries that do not pass a filter function. Used for removing\n * stale tiles from the cache.\n *\n * @param filterFn - Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out.\n */\n filter(filterFn: (tile: Tile) => boolean) {\n const removed = [];\n for (const key in this.data) {\n for (const entry of this.data[key]) {\n if (!filterFn(entry.value)) {\n removed.push(entry);\n }\n }\n }\n for (const r of removed) {\n this.remove(r.value.tileID, r);\n }\n }\n}\n","import {extend} from '../util/util';\nimport {Tile} from './tile';\nimport type {FeatureState} from '@maplibre/maplibre-gl-style-spec';\n\nexport type FeatureStates = {[featureId: string]: FeatureState};\nexport type LayerFeatureStates = {[layer: string]: FeatureStates};\n\n/**\n * @internal\n * SourceFeatureState manages the state and pending changes\n * to features in a source, separated by source layer.\n * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively)\n * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's\n * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations.\n * In deletedStates, all null's denote complete removal of state at that scope\n*/\nexport class SourceFeatureState {\n state: LayerFeatureStates;\n stateChanges: LayerFeatureStates;\n deletedStates: {};\n\n constructor() {\n this.state = {};\n this.stateChanges = {};\n this.deletedStates = {};\n }\n\n updateState(sourceLayer: string, featureId: number | string, newState: any) {\n const feature = String(featureId);\n this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {};\n this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {};\n extend(this.stateChanges[sourceLayer][feature], newState);\n\n if (this.deletedStates[sourceLayer] === null) {\n this.deletedStates[sourceLayer] = {};\n for (const ft in this.state[sourceLayer]) {\n if (ft !== feature) this.deletedStates[sourceLayer][ft] = null;\n }\n } else {\n const featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null;\n if (featureDeletionQueued) {\n this.deletedStates[sourceLayer][feature] = {};\n for (const prop in this.state[sourceLayer][feature]) {\n if (!newState[prop]) this.deletedStates[sourceLayer][feature][prop] = null;\n }\n } else {\n for (const key in newState) {\n const deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null;\n if (deletionInQueue) delete this.deletedStates[sourceLayer][feature][key];\n }\n }\n }\n }\n\n removeFeatureState(sourceLayer: string, featureId?: number | string, key?: string) {\n const sourceLayerDeleted = this.deletedStates[sourceLayer] === null;\n if (sourceLayerDeleted) return;\n\n const feature = String(featureId);\n\n this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {};\n\n if (key && featureId !== undefined) {\n if (this.deletedStates[sourceLayer][feature] !== null) {\n this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {};\n this.deletedStates[sourceLayer][feature][key] = null;\n }\n } else if (featureId !== undefined) {\n const updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature];\n if (updateInQueue) {\n this.deletedStates[sourceLayer][feature] = {};\n for (key in this.stateChanges[sourceLayer][feature]) this.deletedStates[sourceLayer][feature][key] = null;\n\n } else {\n this.deletedStates[sourceLayer][feature] = null;\n }\n } else {\n this.deletedStates[sourceLayer] = null;\n }\n\n }\n\n getState(sourceLayer: string, featureId: number | string) {\n const feature = String(featureId);\n const base = this.state[sourceLayer] || {};\n const changes = this.stateChanges[sourceLayer] || {};\n\n const reconciledState = extend({}, base[feature], changes[feature]);\n\n //return empty object if the whole source layer is awaiting deletion\n if (this.deletedStates[sourceLayer] === null) return {};\n else if (this.deletedStates[sourceLayer]) {\n const featureDeletions = this.deletedStates[sourceLayer][featureId];\n if (featureDeletions === null) return {};\n for (const prop in featureDeletions) delete reconciledState[prop];\n }\n return reconciledState;\n }\n\n initializeTileState(tile: Tile, painter: any) {\n tile.setFeatureState(this.state, painter);\n }\n\n coalesceChanges(tiles: {\n [_ in any]: Tile;\n }, painter: any) {\n //track changes with full state objects, but only for features that got modified\n const featuresChanged: LayerFeatureStates = {};\n\n for (const sourceLayer in this.stateChanges) {\n this.state[sourceLayer] = this.state[sourceLayer] || {};\n const layerStates = {};\n for (const feature in this.stateChanges[sourceLayer]) {\n if (!this.state[sourceLayer][feature]) this.state[sourceLayer][feature] = {};\n extend(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]);\n layerStates[feature] = this.state[sourceLayer][feature];\n }\n featuresChanged[sourceLayer] = layerStates;\n }\n\n for (const sourceLayer in this.deletedStates) {\n this.state[sourceLayer] = this.state[sourceLayer] || {};\n const layerStates = {};\n\n if (this.deletedStates[sourceLayer] === null) {\n for (const ft in this.state[sourceLayer]) {\n layerStates[ft] = {};\n this.state[sourceLayer][ft] = {};\n }\n } else {\n for (const feature in this.deletedStates[sourceLayer]) {\n const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null;\n if (deleteWholeFeatureState) this.state[sourceLayer][feature] = {};\n else {\n for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) {\n delete this.state[sourceLayer][feature][key];\n }\n }\n layerStates[feature] = this.state[sourceLayer][feature];\n }\n }\n\n featuresChanged[sourceLayer] = featuresChanged[sourceLayer] || {};\n extend(featuresChanged[sourceLayer], layerStates);\n }\n\n this.stateChanges = {};\n this.deletedStates = {};\n\n if (Object.keys(featuresChanged).length === 0) return;\n\n for (const id in tiles) {\n const tile = tiles[id];\n tile.setFeatureState(featuresChanged, painter);\n }\n }\n}\n","import {create as createSource} from './source';\n\nimport {Tile} from './tile';\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport {TileCache} from './tile_cache';\nimport {MercatorCoordinate} from '../geo/mercator_coordinate';\nimport {keysDifference} from '../util/util';\nimport {EXTENT} from '../data/extent';\nimport {Context} from '../gl/context';\nimport Point from '@mapbox/point-geometry';\nimport {browser} from '../util/browser';\nimport {OverscaledTileID} from './tile_id';\nimport {SourceFeatureState} from './source_state';\nimport {config} from '../util/config';\n\nimport type {Source} from './source';\nimport type {Map} from '../ui/map';\nimport type {Style} from '../style/style';\nimport type {Dispatcher} from '../util/dispatcher';\nimport type {Transform} from '../geo/transform';\nimport type {TileState} from './tile';\nimport type {SourceSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {MapSourceDataEvent} from '../ui/events';\nimport type {Terrain} from '../render/terrain';\nimport type {CanvasSourceSpecification} from './canvas_source';\n\n/**\n * @internal\n * `SourceCache` is responsible for\n *\n * - creating an instance of `Source`\n * - forwarding events from `Source`\n * - caching tiles loaded from an instance of `Source`\n * - loading the tiles needed to render a given viewport\n * - unloading the cached tiles not needed to render a given viewport\n */\nexport class SourceCache extends Evented {\n id: string;\n dispatcher: Dispatcher;\n map: Map;\n style: Style;\n\n _source: Source;\n\n /**\n * @internal\n * signifies that the TileJSON is loaded if applicable.\n * if the source type does not come with a TileJSON, the flag signifies the\n * source data has loaded (i.e geojson has been tiled on the worker and is ready)\n */\n _sourceLoaded: boolean;\n\n _sourceErrored: boolean;\n _tiles: {[_: string]: Tile};\n _prevLng: number;\n _cache: TileCache;\n _timers: {\n [_ in any]: ReturnType;\n };\n _cacheTimers: {\n [_ in any]: ReturnType;\n };\n _maxTileCacheSize: number;\n _maxTileCacheZoomLevels: number;\n _paused: boolean;\n _shouldReloadOnResume: boolean;\n _coveredTiles: {[_: string]: boolean};\n transform: Transform;\n terrain: Terrain;\n used: boolean;\n usedForTerrain: boolean;\n tileSize: number;\n _state: SourceFeatureState;\n _loadedParentTiles: {[_: string]: Tile};\n _loadedSiblingTiles: {[_: string]: Tile};\n _didEmitContent: boolean;\n _updated: boolean;\n\n static maxUnderzooming: number;\n static maxOverzooming: number;\n\n constructor(id: string, options: SourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher) {\n super();\n this.id = id;\n this.dispatcher = dispatcher;\n\n this.on('data', (e: MapSourceDataEvent) => this._dataHandler(e));\n\n this.on('dataloading', () => {\n this._sourceErrored = false;\n });\n\n this.on('error', () => {\n // Only set _sourceErrored if the source does not have pending loads.\n this._sourceErrored = this._source.loaded();\n });\n\n this._source = createSource(id, options, dispatcher, this);\n\n this._tiles = {};\n this._cache = new TileCache(0, (tile) => this._unloadTile(tile));\n this._timers = {};\n this._cacheTimers = {};\n this._maxTileCacheSize = null;\n this._maxTileCacheZoomLevels = null;\n this._loadedParentTiles = {};\n\n this._coveredTiles = {};\n this._state = new SourceFeatureState();\n this._didEmitContent = false;\n this._updated = false;\n }\n\n onAdd(map: Map) {\n this.map = map;\n this._maxTileCacheSize = map ? map._maxTileCacheSize : null;\n this._maxTileCacheZoomLevels = map ? map._maxTileCacheZoomLevels : null;\n if (this._source && this._source.onAdd) {\n this._source.onAdd(map);\n }\n }\n\n onRemove(map: Map) {\n this.clearTiles();\n if (this._source && this._source.onRemove) {\n this._source.onRemove(map);\n }\n }\n\n /**\n * Return true if no tile data is pending, tiles will not change unless\n * an additional API call is received.\n */\n loaded(): boolean {\n if (this._sourceErrored) { return true; }\n if (!this._sourceLoaded) { return false; }\n if (!this._source.loaded()) { return false; }\n if ((this.used !== undefined || this.usedForTerrain !== undefined) && !this.used && !this.usedForTerrain) { return true; }\n // do not consider as loaded if the update hasn't been called yet (we do not know if we will have any tiles to fetch)\n if (!this._updated) { return false; }\n\n for (const t in this._tiles) {\n const tile = this._tiles[t];\n if (tile.state !== 'loaded' && tile.state !== 'errored')\n return false;\n }\n return true;\n }\n\n getSource(): Source {\n return this._source;\n }\n\n pause() {\n this._paused = true;\n }\n\n resume() {\n if (!this._paused) return;\n const shouldReload = this._shouldReloadOnResume;\n this._paused = false;\n this._shouldReloadOnResume = false;\n if (shouldReload) this.reload();\n if (this.transform) this.update(this.transform, this.terrain);\n }\n\n async _loadTile(tile: Tile, id: string, state: TileState): Promise {\n try {\n await this._source.loadTile(tile);\n this._tileLoaded(tile, id, state);\n } catch (err) {\n tile.state = 'errored';\n if ((err as any).status !== 404) {\n this._source.fire(new ErrorEvent(err, {tile}));\n } else {\n // continue to try loading parent/children tiles if a tile doesn't exist (404)\n this.update(this.transform, this.terrain);\n }\n }\n }\n\n _unloadTile(tile: Tile) {\n if (this._source.unloadTile)\n this._source.unloadTile(tile);\n }\n\n _abortTile(tile: Tile) {\n if (this._source.abortTile)\n this._source.abortTile(tile);\n\n this._source.fire(new Event('dataabort', {tile, coord: tile.tileID, dataType: 'source'}));\n }\n\n serialize() {\n return this._source.serialize();\n }\n\n prepare(context: Context) {\n if (this._source.prepare) {\n this._source.prepare();\n }\n\n this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null);\n for (const i in this._tiles) {\n const tile = this._tiles[i];\n tile.upload(context);\n tile.prepare(this.map.style.imageManager);\n }\n }\n\n /**\n * Return all tile ids ordered with z-order, and cast to numbers\n */\n getIds(): Array {\n return (Object.values(this._tiles) as any).map((tile: Tile) => tile.tileID).sort(compareTileId).map(id => id.key);\n }\n\n getRenderableIds(symbolLayer?: boolean): Array {\n const renderables: Array = [];\n for (const id in this._tiles) {\n if (this._isIdRenderable(id, symbolLayer)) renderables.push(this._tiles[id]);\n }\n if (symbolLayer) {\n return renderables.sort((a_: Tile, b_: Tile) => {\n const a = a_.tileID;\n const b = b_.tileID;\n const rotatedA = (new Point(a.canonical.x, a.canonical.y))._rotate(this.transform.angle);\n const rotatedB = (new Point(b.canonical.x, b.canonical.y))._rotate(this.transform.angle);\n return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x;\n }).map(tile => tile.tileID.key);\n }\n return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key);\n }\n\n hasRenderableParent(tileID: OverscaledTileID) {\n const parentTile = this.findLoadedParent(tileID, 0);\n if (parentTile) {\n return this._isIdRenderable(parentTile.tileID.key);\n }\n return false;\n }\n\n _isIdRenderable(id: string, symbolLayer?: boolean) {\n return this._tiles[id] && this._tiles[id].hasData() &&\n !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade());\n }\n\n reload() {\n if (this._paused) {\n this._shouldReloadOnResume = true;\n return;\n }\n\n this._cache.reset();\n\n for (const i in this._tiles) {\n if (this._tiles[i].state !== 'errored') this._reloadTile(i, 'reloading');\n }\n }\n\n async _reloadTile(id: string, state: TileState) {\n const tile = this._tiles[id];\n\n // this potentially does not address all underlying\n // issues https://github.com/mapbox/mapbox-gl-js/issues/4252\n // - hard to tell without repro steps\n if (!tile) return;\n\n // The difference between \"loading\" tiles and \"reloading\" or \"expired\"\n // tiles is that \"reloading\"/\"expired\" tiles are \"renderable\".\n // Therefore, a \"loading\" tile cannot become a \"reloading\" tile without\n // first becoming a \"loaded\" tile.\n if (tile.state !== 'loading') {\n tile.state = state;\n }\n await this._loadTile(tile, id, state);\n }\n\n _tileLoaded(tile: Tile, id: string, previousState: TileState) {\n tile.timeAdded = browser.now();\n if (previousState === 'expired') tile.refreshedUponExpiration = true;\n this._setTileReloadTimer(id, tile);\n if (this.getSource().type === 'raster-dem' && tile.dem) this._backfillDEM(tile);\n this._state.initializeTileState(tile, this.map ? this.map.painter : null);\n\n if (!tile.aborted) {\n this._source.fire(new Event('data', {dataType: 'source', tile, coord: tile.tileID}));\n }\n }\n\n /**\n * For raster terrain source, backfill DEM to eliminate visible tile boundaries\n */\n _backfillDEM(tile: Tile) {\n const renderables = this.getRenderableIds();\n for (let i = 0; i < renderables.length; i++) {\n const borderId = renderables[i];\n if (tile.neighboringTiles && tile.neighboringTiles[borderId]) {\n const borderTile = this.getTileByID(borderId);\n fillBorder(tile, borderTile);\n fillBorder(borderTile, tile);\n }\n }\n\n function fillBorder(tile, borderTile) {\n tile.needsHillshadePrepare = true;\n tile.needsTerrainPrepare = true;\n let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x;\n const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y;\n const dim = Math.pow(2, tile.tileID.canonical.z);\n const borderId = borderTile.tileID.key;\n if (dx === 0 && dy === 0) return;\n\n if (Math.abs(dy) > 1) {\n return;\n }\n if (Math.abs(dx) > 1) {\n // Adjust the delta coordinate for world wraparound.\n if (Math.abs(dx + dim) === 1) {\n dx += dim;\n } else if (Math.abs(dx - dim) === 1) {\n dx -= dim;\n }\n }\n if (!borderTile.dem || !tile.dem) return;\n tile.dem.backfillBorder(borderTile.dem, dx, dy);\n if (tile.neighboringTiles && tile.neighboringTiles[borderId])\n tile.neighboringTiles[borderId].backfilled = true;\n }\n }\n /**\n * Get a specific tile by TileID\n */\n getTile(tileID: OverscaledTileID): Tile {\n return this.getTileByID(tileID.key);\n }\n\n /**\n * Get a specific tile by id\n */\n getTileByID(id: string): Tile {\n return this._tiles[id];\n }\n\n /**\n * For a given set of tiles, retain children that are loaded and have a zoom\n * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive)\n */\n _retainLoadedChildren(\n idealTiles: {\n [_ in any]: OverscaledTileID;\n },\n zoom: number,\n maxCoveringZoom: number,\n retain: {\n [_ in any]: OverscaledTileID;\n }\n ) {\n for (const id in this._tiles) {\n let tile = this._tiles[id];\n\n // only consider renderable tiles up to maxCoveringZoom\n if (retain[id] ||\n !tile.hasData() ||\n tile.tileID.overscaledZ <= zoom ||\n tile.tileID.overscaledZ > maxCoveringZoom\n ) continue;\n\n // loop through parents and retain the topmost loaded one if found\n let topmostLoadedID = tile.tileID;\n while (tile && tile.tileID.overscaledZ > zoom + 1) {\n const parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1);\n\n tile = this._tiles[parentID.key];\n\n if (tile && tile.hasData()) {\n topmostLoadedID = parentID;\n }\n }\n\n // loop through ancestors of the topmost loaded child to see if there's one that needed it\n let tileID = topmostLoadedID;\n while (tileID.overscaledZ > zoom) {\n tileID = tileID.scaledTo(tileID.overscaledZ - 1);\n\n if (idealTiles[tileID.key]) {\n // found a parent that needed a loaded child; retain that child\n retain[topmostLoadedID.key] = topmostLoadedID;\n break;\n }\n }\n }\n }\n\n /**\n * Find a loaded parent of the given tile (up to minCoveringZoom)\n */\n findLoadedParent(tileID: OverscaledTileID, minCoveringZoom: number): Tile {\n if (tileID.key in this._loadedParentTiles) {\n const parent = this._loadedParentTiles[tileID.key];\n if (parent && parent.tileID.overscaledZ >= minCoveringZoom) {\n return parent;\n } else {\n return null;\n }\n }\n for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) {\n const parentTileID = tileID.scaledTo(z);\n const tile = this._getLoadedTile(parentTileID);\n if (tile) {\n return tile;\n }\n }\n }\n\n /**\n * Find a loaded sibling of the given tile\n */\n findLoadedSibling(tileID: OverscaledTileID): Tile {\n // If a tile with this ID already exists, return it\n return this._getLoadedTile(tileID);\n }\n\n _getLoadedTile(tileID: OverscaledTileID): Tile {\n const tile = this._tiles[tileID.key];\n if (tile && tile.hasData()) {\n return tile;\n }\n // TileCache ignores wrap in lookup.\n const cachedTile = this._cache.getByKey(tileID.wrapped().key);\n return cachedTile;\n }\n\n /**\n * Resizes the tile cache based on the current viewport's size\n * or the maxTileCacheSize option passed during map creation\n *\n * Larger viewports use more tiles and need larger caches. Larger viewports\n * are more likely to be found on devices with more memory and on pages where\n * the map is more important.\n */\n updateCacheSize(transform: Transform) {\n const widthInTiles = Math.ceil(transform.width / this._source.tileSize) + 1;\n const heightInTiles = Math.ceil(transform.height / this._source.tileSize) + 1;\n const approxTilesInView = widthInTiles * heightInTiles;\n const commonZoomRange = this._maxTileCacheZoomLevels === null ?\n config.MAX_TILE_CACHE_ZOOM_LEVELS : this._maxTileCacheZoomLevels;\n const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);\n const maxSize = typeof this._maxTileCacheSize === 'number' ?\n Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize;\n\n this._cache.setMaxSize(maxSize);\n }\n\n handleWrapJump(lng: number) {\n // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify\n // which copy of the world the tile belongs to. For example, at `lng: 10` you\n // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1.\n //\n // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect\n // to see the same thing on the screen (370 degrees and 10 degrees is the same\n // place in the world) but all the TileIDs will have different wrap values.\n //\n // In order to make this transition seamless, we calculate the rounded difference of\n // \"worlds\" between the last frame and the current frame. If the map panned by\n // a world, then we can assign all the tiles new TileIDs with updated wrap values.\n // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered\n // in a different position.\n //\n // This enables us to reuse the tiles at more ideal locations and prevent flickering.\n const prevLng = this._prevLng === undefined ? lng : this._prevLng;\n const lngDifference = lng - prevLng;\n const worldDifference = lngDifference / 360;\n const wrapDelta = Math.round(worldDifference);\n this._prevLng = lng;\n\n if (wrapDelta) {\n const tiles: {[_: string]: Tile} = {};\n for (const key in this._tiles) {\n const tile = this._tiles[key];\n tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);\n tiles[tile.tileID.key] = tile;\n }\n this._tiles = tiles;\n\n // Reset tile reload timers\n for (const id in this._timers) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n this._setTileReloadTimer(id, tile);\n }\n }\n }\n\n _updateCoveredAndRetainedTiles(\n retain: { [_: string]: OverscaledTileID },\n minCoveringZoom: number,\n maxCoveringZoom: number,\n zoom: number,\n idealTileIDs: OverscaledTileID[],\n terrain?: Terrain\n ) {\n const tilesForFading: { [_: string]: OverscaledTileID } = {};\n const fadingTiles = {};\n const ids = Object.keys(retain);\n const now = browser.now();\n for (const id of ids) {\n const tileID = retain[id];\n\n const tile = this._tiles[id];\n\n // when fadeEndTime is 0, the tile is created but registerFadeDuration\n // has not been called, therefore must be kept in fadingTiles dictionary\n // for next round of rendering\n if (!tile || (tile.fadeEndTime !== 0 && tile.fadeEndTime <= now)) {\n continue;\n }\n\n // if the tile is loaded but still fading in, find parents to cross-fade with it\n const parentTile = this.findLoadedParent(tileID, minCoveringZoom);\n const siblingTile = this.findLoadedSibling(tileID);\n const fadeTileRef = parentTile || siblingTile || null;\n if (fadeTileRef) {\n this._addTile(fadeTileRef.tileID);\n tilesForFading[fadeTileRef.tileID.key] = fadeTileRef.tileID;\n }\n\n fadingTiles[id] = tileID;\n }\n\n // for tiles that are still fading in, also find children to cross-fade with\n this._retainLoadedChildren(fadingTiles, zoom, maxCoveringZoom, retain);\n\n for (const id in tilesForFading) {\n if (!retain[id]) {\n // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own.\n this._coveredTiles[id] = true;\n retain[id] = tilesForFading[id];\n }\n }\n\n // disable fading logic in terrain3D mode to avoid rendering two tiles on the same place\n if (terrain) {\n const idealRasterTileIDs: { [_: string]: OverscaledTileID } = {};\n const missingTileIDs: { [_: string]: OverscaledTileID } = {};\n for (const tileID of idealTileIDs) {\n if (this._tiles[tileID.key].hasData())\n idealRasterTileIDs[tileID.key] = tileID;\n else\n missingTileIDs[tileID.key] = tileID;\n }\n // search for a complete set of children for each missing tile\n for (const key in missingTileIDs) {\n const children = missingTileIDs[key].children(this._source.maxzoom);\n if (this._tiles[children[0].key] && this._tiles[children[1].key] && this._tiles[children[2].key] && this._tiles[children[3].key]) {\n idealRasterTileIDs[children[0].key] = retain[children[0].key] = children[0];\n idealRasterTileIDs[children[1].key] = retain[children[1].key] = children[1];\n idealRasterTileIDs[children[2].key] = retain[children[2].key] = children[2];\n idealRasterTileIDs[children[3].key] = retain[children[3].key] = children[3];\n delete missingTileIDs[key];\n }\n }\n // search for parent or sibling for each missing tile\n for (const key in missingTileIDs) {\n const tileID = missingTileIDs[key];\n const parentTile = this.findLoadedParent(tileID, this._source.minzoom);\n const siblingTile = this.findLoadedSibling(tileID);\n const fadeTileRef = parentTile || siblingTile || null;\n if (fadeTileRef) {\n idealRasterTileIDs[fadeTileRef.tileID.key] = retain[fadeTileRef.tileID.key] = fadeTileRef.tileID;\n // remove idealTiles which would be rendered twice\n for (const key in idealRasterTileIDs) {\n if (idealRasterTileIDs[key].isChildOf(fadeTileRef.tileID)) delete idealRasterTileIDs[key];\n }\n }\n }\n // cover all tiles which are not needed\n for (const key in this._tiles) {\n if (!idealRasterTileIDs[key]) this._coveredTiles[key] = true;\n }\n }\n }\n\n /**\n * Removes tiles that are outside the viewport and adds new tiles that\n * are inside the viewport.\n */\n update(transform: Transform, terrain?: Terrain) {\n if (!this._sourceLoaded || this._paused) {\n return;\n }\n this.transform = transform;\n this.terrain = terrain;\n\n this.updateCacheSize(transform);\n this.handleWrapJump(this.transform.center.lng);\n\n // Covered is a list of retained tiles who's areas are fully covered by other,\n // better, retained tiles. They are not drawn separately.\n this._coveredTiles = {};\n\n let idealTileIDs: OverscaledTileID[];\n\n if (!this.used && !this.usedForTerrain) {\n idealTileIDs = [];\n } else if (this._source.tileID) {\n idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID)\n .map((unwrapped) => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));\n } else {\n idealTileIDs = transform.coveringTiles({\n tileSize: this.usedForTerrain ? this.tileSize : this._source.tileSize,\n minzoom: this._source.minzoom,\n maxzoom: this._source.maxzoom,\n roundZoom: this.usedForTerrain ? false : this._source.roundZoom,\n reparseOverscaled: this._source.reparseOverscaled,\n terrain\n });\n\n if (this._source.hasTile) {\n idealTileIDs = idealTileIDs.filter((coord) => (this._source.hasTile as any)(coord));\n }\n }\n\n // Determine the overzooming/underzooming amounts.\n const zoom = transform.coveringZoomLevel(this._source);\n const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom);\n const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom);\n\n // When sourcecache is used for terrain also load parent tiles to avoid flickering when zooming out\n if (this.usedForTerrain) {\n const parents = {};\n for (const tileID of idealTileIDs) {\n if (tileID.canonical.z > this._source.minzoom) {\n const parent = tileID.scaledTo(tileID.canonical.z - 1);\n parents[parent.key] = parent;\n // load very low zoom to calculate tile visibility in transform.coveringTiles and high zoomlevels correct\n const parent2 = tileID.scaledTo(Math.max(this._source.minzoom, Math.min(tileID.canonical.z, 5)));\n parents[parent2.key] = parent2;\n }\n }\n idealTileIDs = idealTileIDs.concat(Object.values(parents));\n }\n\n const noPendingDataEmissions = idealTileIDs.length === 0 && !this._updated && this._didEmitContent;\n this._updated = true;\n // if we won't have any tiles to fetch and content is already emitted\n // there will be no more data emissions, so we need to emit the event with isSourceLoaded = true\n if (noPendingDataEmissions) {\n this.fire(new Event('data', {sourceDataType: 'idle', dataType: 'source', sourceId: this.id}));\n }\n\n // Retain is a list of tiles that we shouldn't delete, even if they are not\n // the most ideal tile for the current viewport. This may include tiles like\n // parent or child tiles that are *already* loaded.\n const retain = this._updateRetainedTiles(idealTileIDs, zoom);\n\n if (isRasterType(this._source.type)) {\n this._updateCoveredAndRetainedTiles(retain, minCoveringZoom, maxCoveringZoom, zoom, idealTileIDs, terrain);\n }\n\n for (const retainedId in retain) {\n // Make sure retained tiles always clear any existing fade holds\n // so that if they're removed again their fade timer starts fresh.\n this._tiles[retainedId].clearFadeHold();\n }\n\n // Remove the tiles we don't need anymore.\n const remove = keysDifference(this._tiles, retain);\n for (const tileID of remove) {\n const tile = this._tiles[tileID];\n if (tile.hasSymbolBuckets && !tile.holdingForFade()) {\n tile.setHoldDuration(this.map._fadeDuration);\n } else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) {\n this._removeTile(tileID);\n }\n }\n\n // Construct caches of loaded parents & siblings\n this._updateLoadedParentTileCache();\n this._updateLoadedSiblingTileCache();\n }\n\n releaseSymbolFadeTiles() {\n for (const id in this._tiles) {\n if (this._tiles[id].holdingForFade()) {\n this._removeTile(id);\n }\n }\n }\n\n _updateRetainedTiles(idealTileIDs: Array, zoom: number): {[_: string]: OverscaledTileID} {\n const retain: {[_: string]: OverscaledTileID} = {};\n const checked: {[_: string]: boolean} = {};\n const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom);\n const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom);\n\n const missingTiles = {};\n for (const tileID of idealTileIDs) {\n const tile = this._addTile(tileID);\n\n // retain the tile even if it's not loaded because it's an ideal tile.\n retain[tileID.key] = tileID;\n\n if (tile.hasData()) continue;\n\n if (zoom < this._source.maxzoom) {\n // save missing tiles that potentially have loaded children\n missingTiles[tileID.key] = tileID;\n }\n }\n\n // retain any loaded children of ideal tiles up to maxCoveringZoom\n this._retainLoadedChildren(missingTiles, zoom, maxCoveringZoom, retain);\n\n for (const tileID of idealTileIDs) {\n let tile = this._tiles[tileID.key];\n\n if (tile.hasData()) continue;\n\n // The tile we require is not yet loaded or does not exist;\n // Attempt to find children that fully cover it.\n\n if (zoom + 1 > this._source.maxzoom) {\n // We're looking for an overzoomed child tile.\n const childCoord = tileID.children(this._source.maxzoom)[0];\n const childTile = this.getTile(childCoord);\n if (!!childTile && childTile.hasData()) {\n retain[childCoord.key] = childCoord;\n continue; // tile is covered by overzoomed child\n }\n } else {\n // check if all 4 immediate children are loaded (i.e. the missing ideal tile is covered)\n const children = tileID.children(this._source.maxzoom);\n\n if (retain[children[0].key] &&\n retain[children[1].key] &&\n retain[children[2].key] &&\n retain[children[3].key]) continue; // tile is covered by children\n }\n\n // We couldn't find child tiles that entirely cover the ideal tile; look for parents now.\n\n // As we ascend up the tile pyramid of the ideal tile, we check whether the parent\n // tile has been previously requested (and errored because we only loop over tiles with no data)\n // in order to determine if we need to request its parent.\n let parentWasRequested = tile.wasRequested();\n\n for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) {\n const parentId = tileID.scaledTo(overscaledZ);\n\n // Break parent tile ascent if this route has been previously checked by another child.\n if (checked[parentId.key]) break;\n checked[parentId.key] = true;\n\n tile = this.getTile(parentId);\n if (!tile && parentWasRequested) {\n tile = this._addTile(parentId);\n }\n if (tile) {\n const hasData = tile.hasData();\n if (hasData || !this.map?.cancelPendingTileRequestsWhileZooming || parentWasRequested) {\n retain[parentId.key] = parentId;\n }\n // Save the current values, since they're the parent of the next iteration\n // of the parent tile ascent loop.\n parentWasRequested = tile.wasRequested();\n if (hasData) break;\n }\n }\n }\n\n return retain;\n }\n\n _updateLoadedParentTileCache() {\n this._loadedParentTiles = {};\n\n for (const tileKey in this._tiles) {\n const path = [];\n let parentTile: Tile;\n let currentId = this._tiles[tileKey].tileID;\n\n // Find the closest loaded ancestor by traversing the tile tree towards the root and\n // caching results along the way\n while (currentId.overscaledZ > 0) {\n\n // Do we have a cached result from previous traversals?\n if (currentId.key in this._loadedParentTiles) {\n parentTile = this._loadedParentTiles[currentId.key];\n break;\n }\n\n path.push(currentId.key);\n\n // Is the parent loaded?\n const parentId = currentId.scaledTo(currentId.overscaledZ - 1);\n parentTile = this._getLoadedTile(parentId);\n if (parentTile) {\n break;\n }\n\n currentId = parentId;\n }\n\n // Cache the result of this traversal to all newly visited tiles\n for (const key of path) {\n this._loadedParentTiles[key] = parentTile;\n }\n }\n }\n\n /**\n * Update the cache of loaded sibling tiles\n *\n * Sibling tiles are tiles that share the same zoom level and\n * x/y position but have different wrap values\n * Maintaining sibling tile cache allows fading from old to new tiles\n * of the same position and zoom level\n */\n _updateLoadedSiblingTileCache() {\n this._loadedSiblingTiles = {};\n\n for (const tileKey in this._tiles) {\n const currentId = this._tiles[tileKey].tileID;\n const siblingTile: Tile = this._getLoadedTile(currentId);\n this._loadedSiblingTiles[currentId.key] = siblingTile;\n }\n }\n\n /**\n * Add a tile, given its coordinate, to the pyramid.\n */\n _addTile(tileID: OverscaledTileID): Tile {\n let tile = this._tiles[tileID.key];\n if (tile)\n return tile;\n\n tile = this._cache.getAndRemove(tileID);\n if (tile) {\n this._setTileReloadTimer(tileID.key, tile);\n // set the tileID because the cached tile could have had a different wrap value\n tile.tileID = tileID;\n this._state.initializeTileState(tile, this.map ? this.map.painter : null);\n if (this._cacheTimers[tileID.key]) {\n clearTimeout(this._cacheTimers[tileID.key]);\n delete this._cacheTimers[tileID.key];\n this._setTileReloadTimer(tileID.key, tile);\n }\n }\n\n const cached = tile;\n\n if (!tile) {\n tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor());\n this._loadTile(tile, tileID.key, tile.state);\n }\n\n tile.uses++;\n this._tiles[tileID.key] = tile;\n if (!cached) {\n this._source.fire(new Event('dataloading', {tile, coord: tile.tileID, dataType: 'source'}));\n }\n\n return tile;\n }\n\n _setTileReloadTimer(id: string, tile: Tile) {\n if (id in this._timers) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n\n const expiryTimeout = tile.getExpiryTimeout();\n if (expiryTimeout) {\n this._timers[id] = setTimeout(() => {\n this._reloadTile(id, 'expired');\n delete this._timers[id];\n }, expiryTimeout);\n }\n }\n\n /**\n * Remove a tile, given its id, from the pyramid\n */\n _removeTile(id: string) {\n const tile = this._tiles[id];\n if (!tile)\n return;\n\n tile.uses--;\n delete this._tiles[id];\n if (this._timers[id]) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n\n if (tile.uses > 0)\n return;\n\n if (tile.hasData() && tile.state !== 'reloading') {\n this._cache.add(tile.tileID, tile, tile.getExpiryTimeout());\n } else {\n tile.aborted = true;\n this._abortTile(tile);\n this._unloadTile(tile);\n }\n }\n\n /** @internal */\n private _dataHandler(e: MapSourceDataEvent) {\n\n const eventSourceDataType = e.sourceDataType;\n if (e.dataType === 'source' && eventSourceDataType === 'metadata') {\n this._sourceLoaded = true;\n }\n\n // for sources with mutable data, this event fires when the underlying data\n // to a source is changed. (i.e. GeoJSONSource#setData and ImageSource#serCoordinates)\n if (this._sourceLoaded && !this._paused && e.dataType === 'source' && eventSourceDataType === 'content') {\n this.reload();\n if (this.transform) {\n this.update(this.transform, this.terrain);\n }\n\n this._didEmitContent = true;\n }\n }\n\n /**\n * Remove all tiles from this pyramid\n */\n clearTiles() {\n this._shouldReloadOnResume = false;\n this._paused = false;\n\n for (const id in this._tiles)\n this._removeTile(id);\n\n this._cache.reset();\n }\n\n /**\n * Search through our current tiles and attempt to find the tiles that\n * cover the given bounds.\n * @param pointQueryGeometry - coordinates of the corners of bounding rectangle\n * @returns result items have `{tile, minX, maxX, minY, maxY}`, where min/max bounding values are the given bounds transformed in into the coordinate space of this tile.\n */\n tilesIn(pointQueryGeometry: Array, maxPitchScaleFactor: number, has3DLayer: boolean): any[] {\n\n const tileResults = [];\n\n const transform = this.transform;\n if (!transform) return tileResults;\n\n const cameraPointQueryGeometry = has3DLayer ?\n transform.getCameraQueryGeometry(pointQueryGeometry) :\n pointQueryGeometry;\n\n const queryGeometry = pointQueryGeometry.map((p: Point) => transform.pointCoordinate(p, this.terrain));\n const cameraQueryGeometry = cameraPointQueryGeometry.map((p: Point) => transform.pointCoordinate(p, this.terrain));\n\n const ids = this.getIds();\n\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (const p of cameraQueryGeometry) {\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x);\n maxY = Math.max(maxY, p.y);\n }\n\n for (let i = 0; i < ids.length; i++) {\n const tile = this._tiles[ids[i]];\n if (tile.holdingForFade()) {\n // Tiles held for fading are covered by tiles that are closer to ideal\n continue;\n }\n const tileID = tile.tileID;\n const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);\n const queryPadding = maxPitchScaleFactor * tile.queryPadding * EXTENT / tile.tileSize / scale;\n\n const tileSpaceBounds = [\n tileID.getTilePoint(new MercatorCoordinate(minX, minY)),\n tileID.getTilePoint(new MercatorCoordinate(maxX, maxY))\n ];\n\n if (tileSpaceBounds[0].x - queryPadding < EXTENT && tileSpaceBounds[0].y - queryPadding < EXTENT &&\n tileSpaceBounds[1].x + queryPadding >= 0 && tileSpaceBounds[1].y + queryPadding >= 0) {\n\n const tileSpaceQueryGeometry: Array = queryGeometry.map((c) => tileID.getTilePoint(c));\n const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c));\n\n tileResults.push({\n tile,\n tileID,\n queryGeometry: tileSpaceQueryGeometry,\n cameraQueryGeometry: tileSpaceCameraQueryGeometry,\n scale\n });\n }\n }\n\n return tileResults;\n }\n\n getVisibleCoordinates(symbolLayer?: boolean): Array {\n const coords = this.getRenderableIds(symbolLayer).map((id) => this._tiles[id].tileID);\n for (const coord of coords) {\n coord.posMatrix = this.transform.calculatePosMatrix(coord.toUnwrapped());\n }\n return coords;\n }\n\n hasTransition() {\n if (this._source.hasTransition()) {\n return true;\n }\n\n if (isRasterType(this._source.type)) {\n const now = browser.now();\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n if (tile.fadeEndTime >= now) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Set the value of a particular state for a feature\n */\n setFeatureState(sourceLayer: string, featureId: number | string, state: any) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n this._state.updateState(sourceLayer, featureId, state);\n }\n\n /**\n * Resets the value of a particular state key for a feature\n */\n removeFeatureState(sourceLayer?: string, featureId?: number | string, key?: string) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n this._state.removeFeatureState(sourceLayer, featureId, key);\n }\n\n /**\n * Get the entire state object for a feature\n */\n getFeatureState(sourceLayer: string, featureId: number | string) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n return this._state.getState(sourceLayer, featureId);\n }\n\n /**\n * Sets the set of keys that the tile depends on. This allows tiles to\n * be reloaded when their dependencies change.\n */\n setDependencies(tileKey: string, namespace: string, dependencies: Array) {\n const tile = this._tiles[tileKey];\n if (tile) {\n tile.setDependencies(namespace, dependencies);\n }\n }\n\n /**\n * Reloads all tiles that depend on the given keys.\n */\n reloadTilesForDependencies(namespaces: Array, keys: Array) {\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n if (tile.hasDependency(namespaces, keys)) {\n this._reloadTile(id, 'reloading');\n }\n }\n this._cache.filter(tile => !tile.hasDependency(namespaces, keys));\n }\n}\n\nSourceCache.maxOverzooming = 10;\nSourceCache.maxUnderzooming = 3;\n\nfunction compareTileId(a: OverscaledTileID, b: OverscaledTileID): number {\n // Different copies of the world are sorted based on their distance to the center.\n // Wrap values are converted to unsigned distances by reserving odd number for copies\n // with negative wrap and even numbers for copies with positive wrap.\n const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0);\n const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0);\n return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x;\n}\n\nfunction isRasterType(type) {\n return type === 'raster' || type === 'image' || type === 'video';\n}\n","import {clamp} from '../util/util';\nimport Point from '@mapbox/point-geometry';\n\nexport class PathInterpolator {\n points: Array;\n length: number;\n paddedLength: number;\n padding: number;\n _distances: Array;\n\n constructor(points_?: Array | null, padding_?: number | null) {\n this.reset(points_, padding_);\n }\n\n reset(points_?: Array | null, padding_?: number | null) {\n this.points = points_ || [];\n\n // Compute cumulative distance from first point to every other point in the segment.\n // Last entry in the array is total length of the path\n this._distances = [0.0];\n\n for (let i = 1; i < this.points.length; i++) {\n this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]);\n }\n\n this.length = this._distances[this._distances.length - 1];\n this.padding = Math.min(padding_ || 0, this.length * 0.5);\n this.paddedLength = this.length - this.padding * 2.0;\n }\n\n lerp(t: number): Point {\n if (this.points.length === 1) {\n return this.points[0];\n }\n\n t = clamp(t, 0, 1);\n\n // Find the correct segment [p0, p1] where p0 <= x < p1\n let currentIndex = 1;\n let distOfCurrentIdx = this._distances[currentIndex];\n const distToTarget = t * this.paddedLength + this.padding;\n\n while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) {\n distOfCurrentIdx = this._distances[++currentIndex];\n }\n\n // Interpolate between the two points of the segment\n const idxOfPrevPoint = currentIndex - 1;\n const distOfPrevIdx = this._distances[idxOfPrevPoint];\n const segmentLength = distOfCurrentIdx - distOfPrevIdx;\n const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0;\n\n return this.points[idxOfPrevPoint].mult(1.0 - segmentT).add(this.points[currentIndex].mult(segmentT));\n }\n}\n","import type {OverlapMode} from '../style/style_layer/overlap_mode';\n\ntype QueryArgs = {\n hitTest: boolean;\n overlapMode?: OverlapMode;\n circle?: {\n x: number;\n y: number;\n radius: number;\n };\n seenUids: {\n box: {\n [_: number]: boolean;\n };\n circle: {\n [_: number]: boolean;\n };\n };\n};\n\ntype QueryResult = {\n key: T;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n};\n\n/**\n * A key for the grid\n */\nexport type GridKey = {\n overlapMode?: OverlapMode;\n}\n\nfunction overlapAllowed(overlapA: OverlapMode, overlapB: OverlapMode): boolean {\n let allowed = true;\n\n if (overlapA === 'always') {\n // symbol A using 'always' overlap - allowed to overlap anything.\n } else if (overlapA === 'never' || overlapB === 'never') {\n // symbol A using 'never' overlap - can't overlap anything\n // symbol A using 'cooperative' overlap - can overlap 'always' or 'cooperative' symbol; can't overlap 'never'\n allowed = false;\n }\n\n return allowed;\n}\n\n/**\n * @internal\n * GridIndex is a data structure for testing the intersection of\n * circles and rectangles in a 2d plane.\n * It is optimized for rapid insertion and querying.\n * GridIndex splits the plane into a set of \"cells\" and keeps track\n * of which geometries intersect with each cell. At query time,\n * full geometry comparisons are only done for items that share\n * at least one cell. As long as the geometries are relatively\n * uniformly distributed across the plane, this greatly reduces\n * the number of comparisons necessary.\n */\nexport class GridIndex {\n circleKeys: Array;\n boxKeys: Array;\n boxCells: Array>;\n circleCells: Array>;\n bboxes: Array;\n circles: Array;\n xCellCount: number;\n yCellCount: number;\n width: number;\n height: number;\n xScale: number;\n yScale: number;\n boxUid: number;\n circleUid: number;\n\n constructor (width: number, height: number, cellSize: number) {\n const boxCells = this.boxCells = [];\n const circleCells = this.circleCells = [];\n\n // More cells -> fewer geometries to check per cell, but items tend\n // to be split across more cells.\n // Sweet spot allows most small items to fit in one cell\n this.xCellCount = Math.ceil(width / cellSize);\n this.yCellCount = Math.ceil(height / cellSize);\n\n for (let i = 0; i < this.xCellCount * this.yCellCount; i++) {\n boxCells.push([]);\n circleCells.push([]);\n }\n this.circleKeys = [];\n this.boxKeys = [];\n this.bboxes = [];\n this.circles = [];\n\n this.width = width;\n this.height = height;\n this.xScale = this.xCellCount / width;\n this.yScale = this.yCellCount / height;\n this.boxUid = 0;\n this.circleUid = 0;\n }\n\n keysLength() {\n return this.boxKeys.length + this.circleKeys.length;\n }\n\n insert(key: T, x1: number, y1: number, x2: number, y2: number) {\n this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++);\n this.boxKeys.push(key);\n this.bboxes.push(x1);\n this.bboxes.push(y1);\n this.bboxes.push(x2);\n this.bboxes.push(y2);\n }\n\n insertCircle(key: T, x: number, y: number, radius: number) {\n // Insert circle into grid for all cells in the circumscribing square\n // It's more than necessary (by a factor of 4/PI), but fast to insert\n this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++);\n this.circleKeys.push(key);\n this.circles.push(x);\n this.circles.push(y);\n this.circles.push(radius);\n }\n\n private _insertBoxCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {\n this.boxCells[cellIndex].push(uid);\n }\n\n private _insertCircleCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {\n this.circleCells[cellIndex].push(uid);\n }\n\n private _query(x1: number, y1: number, x2: number, y2: number, hitTest: boolean, overlapMode: OverlapMode, predicate?: (key: T) => boolean): Array> {\n if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {\n return [];\n }\n const result: Array> = [];\n if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) {\n if (hitTest) {\n // Covers the entire grid, so collides with everything\n return [{\n key: null,\n x1,\n y1,\n x2,\n y2\n }];\n }\n for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) {\n result.push({\n key: this.boxKeys[boxUid],\n x1: this.bboxes[boxUid * 4],\n y1: this.bboxes[boxUid * 4 + 1],\n x2: this.bboxes[boxUid * 4 + 2],\n y2: this.bboxes[boxUid * 4 + 3]\n });\n }\n for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) {\n const x = this.circles[circleUid * 3];\n const y = this.circles[circleUid * 3 + 1];\n const radius = this.circles[circleUid * 3 + 2];\n result.push({\n key: this.circleKeys[circleUid],\n x1: x - radius,\n y1: y - radius,\n x2: x + radius,\n y2: y + radius\n });\n }\n } else {\n const queryArgs: QueryArgs = {\n hitTest,\n overlapMode,\n seenUids: {box: {}, circle: {}}\n };\n this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate);\n }\n\n return result;\n }\n\n query(x1: number, y1: number, x2: number, y2: number): Array> {\n return this._query(x1, y1, x2, y2, false, null);\n }\n\n hitTest(x1: number, y1: number, x2: number, y2: number, overlapMode: OverlapMode, predicate?: (key: T) => boolean): boolean {\n return this._query(x1, y1, x2, y2, true, overlapMode, predicate).length > 0;\n }\n\n hitTestCircle(x: number, y: number, radius: number, overlapMode: OverlapMode, predicate?: (key: T) => boolean): boolean {\n // Insert circle into grid for all cells in the circumscribing square\n // It's more than necessary (by a factor of 4/PI), but fast to insert\n const x1 = x - radius;\n const x2 = x + radius;\n const y1 = y - radius;\n const y2 = y + radius;\n if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {\n return false;\n }\n\n // Box query early exits if the bounding box is larger than the grid, but we don't do\n // the equivalent calculation for circle queries because early exit is less likely\n // and the calculation is more expensive\n const result: boolean[] = [];\n const queryArgs: QueryArgs = {\n hitTest: true,\n overlapMode,\n circle: {x, y, radius},\n seenUids: {box: {}, circle: {}}\n };\n this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate);\n return result.length > 0;\n }\n\n private _queryCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: Array>, queryArgs: QueryArgs, predicate?: (key: T) => boolean): boolean {\n const {seenUids, hitTest, overlapMode} = queryArgs;\n const boxCell = this.boxCells[cellIndex];\n\n if (boxCell !== null) {\n const bboxes = this.bboxes;\n for (const boxUid of boxCell) {\n if (!seenUids.box[boxUid]) {\n seenUids.box[boxUid] = true;\n const offset = boxUid * 4;\n const key = this.boxKeys[boxUid];\n\n if ((x1 <= bboxes[offset + 2]) &&\n (y1 <= bboxes[offset + 3]) &&\n (x2 >= bboxes[offset + 0]) &&\n (y2 >= bboxes[offset + 1]) &&\n (!predicate || predicate(key))) {\n if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) {\n result.push({\n key,\n x1: bboxes[offset],\n y1: bboxes[offset + 1],\n x2: bboxes[offset + 2],\n y2: bboxes[offset + 3]\n });\n if (hitTest) {\n // true return value stops the query after first match\n return true;\n }\n }\n }\n }\n }\n }\n const circleCell = this.circleCells[cellIndex];\n if (circleCell !== null) {\n const circles = this.circles;\n for (const circleUid of circleCell) {\n if (!seenUids.circle[circleUid]) {\n seenUids.circle[circleUid] = true;\n const offset = circleUid * 3;\n const key = this.circleKeys[circleUid];\n\n if (this._circleAndRectCollide(\n circles[offset],\n circles[offset + 1],\n circles[offset + 2],\n x1,\n y1,\n x2,\n y2) &&\n (!predicate || predicate(key))) {\n if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) {\n const x = circles[offset];\n const y = circles[offset + 1];\n const radius = circles[offset + 2];\n result.push({\n key,\n x1: x - radius,\n y1: y - radius,\n x2: x + radius,\n y2: y + radius\n });\n if (hitTest) {\n // true return value stops the query after first match\n return true;\n }\n }\n }\n }\n }\n }\n\n // false return to continue query\n return false;\n }\n\n private _queryCellCircle(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: Array, queryArgs: QueryArgs, predicate?: (key: T) => boolean): boolean {\n const {circle, seenUids, overlapMode} = queryArgs;\n const boxCell = this.boxCells[cellIndex];\n\n if (boxCell !== null) {\n const bboxes = this.bboxes;\n for (const boxUid of boxCell) {\n if (!seenUids.box[boxUid]) {\n seenUids.box[boxUid] = true;\n const offset = boxUid * 4;\n const key = this.boxKeys[boxUid];\n if (this._circleAndRectCollide(\n circle.x,\n circle.y,\n circle.radius,\n bboxes[offset + 0],\n bboxes[offset + 1],\n bboxes[offset + 2],\n bboxes[offset + 3]) &&\n (!predicate || predicate(key)) &&\n !overlapAllowed(overlapMode, key.overlapMode)) {\n result.push(true);\n return true;\n }\n }\n }\n }\n\n const circleCell = this.circleCells[cellIndex];\n if (circleCell !== null) {\n const circles = this.circles;\n for (const circleUid of circleCell) {\n if (!seenUids.circle[circleUid]) {\n seenUids.circle[circleUid] = true;\n const offset = circleUid * 3;\n const key = this.circleKeys[circleUid];\n if (this._circlesCollide(\n circles[offset],\n circles[offset + 1],\n circles[offset + 2],\n circle.x,\n circle.y,\n circle.radius) &&\n (!predicate || predicate(key)) &&\n !overlapAllowed(overlapMode, key.overlapMode)) {\n result.push(true);\n return true;\n }\n }\n }\n }\n }\n\n private _forEachCell(\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n fn: (x1: number, y1: number, x2: number, y2: number, cellIndex: number, arg1: TArg, arg2?: QueryArgs, predicate?: (key: T) => boolean) => boolean | void,\n arg1: TArg,\n arg2?: QueryArgs,\n predicate?: (key: T) => boolean) {\n const cx1 = this._convertToXCellCoord(x1);\n const cy1 = this._convertToYCellCoord(y1);\n const cx2 = this._convertToXCellCoord(x2);\n const cy2 = this._convertToYCellCoord(y2);\n\n for (let x = cx1; x <= cx2; x++) {\n for (let y = cy1; y <= cy2; y++) {\n const cellIndex = this.xCellCount * y + x;\n if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) return;\n }\n }\n }\n\n private _convertToXCellCoord(x: number) {\n return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale)));\n }\n\n private _convertToYCellCoord(y: number) {\n return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale)));\n }\n\n private _circlesCollide(x1: number, y1: number, r1: number, x2: number, y2: number, r2: number): boolean {\n const dx = x2 - x1;\n const dy = y2 - y1;\n const bothRadii = r1 + r2;\n return (bothRadii * bothRadii) > (dx * dx + dy * dy);\n }\n\n private _circleAndRectCollide(\n circleX: number,\n circleY: number,\n radius: number,\n x1: number,\n y1: number,\n x2: number,\n y2: number\n ): boolean {\n const halfRectWidth = (x2 - x1) / 2;\n const distX = Math.abs(circleX - (x1 + halfRectWidth));\n if (distX > (halfRectWidth + radius)) {\n return false;\n }\n\n const halfRectHeight = (y2 - y1) / 2;\n const distY = Math.abs(circleY - (y1 + halfRectHeight));\n if (distY > (halfRectHeight + radius)) {\n return false;\n }\n\n if (distX <= halfRectWidth || distY <= halfRectHeight) {\n return true;\n }\n\n const dx = distX - halfRectWidth;\n const dy = distY - halfRectHeight;\n return (dx * dx + dy * dy <= (radius * radius));\n }\n}\n","import Point from '@mapbox/point-geometry';\n\nimport {mat4, vec4} from 'gl-matrix';\nimport * as symbolSize from './symbol_size';\nimport {addDynamicAttributes} from '../data/bucket/symbol_bucket';\n\nimport type {Painter} from '../render/painter';\nimport type {Transform} from '../geo/transform';\nimport type {SymbolBucket} from '../data/bucket/symbol_bucket';\nimport type {\n GlyphOffsetArray,\n SymbolLineVertexArray,\n SymbolDynamicLayoutArray\n} from '../data/array_types.g';\nimport {WritingMode} from '../symbol/shaping';\nimport {findLineIntersection} from '../util/util';\nimport {UnwrappedTileID} from '../source/tile_id';\nimport {Projection} from '../geo/projection/projection';\n\nexport {\n updateLineLabels,\n hideGlyphs,\n getLabelPlaneMatrix,\n getGlCoordMatrix,\n project,\n getPerspectiveRatio,\n placeFirstAndLastGlyph,\n placeGlyphAlongLine,\n xyTransformMat4,\n projectLineVertexToViewport as projectVertexToViewport,\n projectTileCoordinatesToViewport,\n findOffsetIntersectionPoint,\n transformToOffsetNormal,\n};\n\n/**\n * The result of projecting a point to the screen, with some additional information about the projection.\n */\nexport type PointProjection = {\n /**\n * The projected point.\n */\n point: Point;\n /**\n * The original W component of the projection.\n */\n signedDistanceFromCamera: number;\n /**\n * For complex projections (such as globe), true if the point is occluded by the projection, such as by being on the backfacing side of the globe.\n */\n isOccluded: boolean;\n};\n\n/*\n * # Overview of coordinate spaces\n *\n * ## Tile coordinate spaces\n * Each label has an anchor. Some labels have corresponding line geometries.\n * The points for both anchors and lines are stored in tile units. Each tile has it's own\n * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right.\n *\n * ## Clip space (GL coordinate space)\n * At the end of everything, the vertex shader needs to produce a position in clip space,\n * which is (-1, 1) at the top left and (1, -1) in the bottom right.\n * In the depth buffer, values are between 0 (near plane) to 1 (far plane).\n *\n * ## Map pixel coordinate spaces\n * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is\n * whatever counts as 1 pixel at the current zoom.\n * This space is used for pitch-alignment=map, rotation-alignment=map\n *\n * ## Rotated map pixel coordinate spaces\n * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile.\n * This space is used for pitch-alignment=map, rotation-alignment=viewport\n *\n * ## Viewport pixel coordinate space\n * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner\n * of the canvas. This space is used for pitch-alignment=viewport\n *\n *\n * # Vertex projection\n * It goes roughly like this:\n * 1. project the anchor and line from tile units into the correct label coordinate space\n * - map pixel space pitch-alignment=map rotation-alignment=map\n * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport\n * - viewport pixel space pitch-alignment=viewport rotation-alignment=*\n * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor.\n * 3. add the glyph's corner offset to the point from step 3\n * 4. convert from the label coordinate space to clip space\n *\n * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work).\n * This is what `u_label_plane_matrix` is used for.\n * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry.\n * This is what `updateLineLabels(...)` does.\n * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix.\n *\n * Steps 3 and 4 are done in the shaders for all labels.\n */\n\n/*\n * Returns a matrix for converting from tile units to the correct label coordinate space.\n */\nfunction getLabelPlaneMatrix(posMatrix: mat4,\n pitchWithMap: boolean,\n rotateWithMap: boolean,\n transform: Transform,\n pixelsToTileUnits: number) {\n const m = mat4.create();\n if (pitchWithMap) {\n mat4.scale(m, m, [1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1]);\n if (!rotateWithMap) {\n mat4.rotateZ(m, m, transform.angle);\n }\n } else {\n mat4.multiply(m, transform.labelPlaneMatrix, posMatrix);\n }\n return m;\n}\n\n/*\n * Returns a matrix for converting from the correct label coordinate space to clip space.\n */\nfunction getGlCoordMatrix(posMatrix: mat4,\n pitchWithMap: boolean,\n rotateWithMap: boolean,\n transform: Transform,\n pixelsToTileUnits: number) {\n if (pitchWithMap) {\n const m = mat4.clone(posMatrix);\n mat4.scale(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]);\n if (!rotateWithMap) {\n mat4.rotateZ(m, m, -transform.angle);\n }\n return m;\n } else {\n return transform.glCoordMatrix;\n }\n}\n\nfunction project(x: number, y: number, matrix: mat4, getElevation?: (x: number, y: number) => number): PointProjection {\n let pos;\n if (getElevation) { // slow because of handle z-index\n pos = [x, y, getElevation(x, y), 1] as vec4;\n vec4.transformMat4(pos, pos, matrix);\n } else { // fast because of ignore z-index\n pos = [x, y, 0, 1] as vec4;\n xyTransformMat4(pos, pos, matrix);\n }\n const w = pos[3];\n return {\n point: new Point(pos[0] / w, pos[1] / w),\n signedDistanceFromCamera: w,\n isOccluded: false\n };\n}\n\nfunction getPerspectiveRatio(cameraToCenterDistance: number, signedDistanceFromCamera: number): number {\n return 0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera);\n}\n\nfunction isVisible(p: Point,\n clippingBuffer: [number, number]) {\n const inPaddedViewport = (\n p.x >= -clippingBuffer[0] &&\n p.x <= clippingBuffer[0] &&\n p.y >= -clippingBuffer[1] &&\n p.y <= clippingBuffer[1]);\n return inPaddedViewport;\n}\n\n/*\n * Update the `dynamicLayoutVertexBuffer` for the buffer with the correct glyph positions for the current map view.\n * This is only run on labels that are aligned with lines. Horizontal labels are handled entirely in the shader.\n */\nfunction updateLineLabels(bucket: SymbolBucket,\n posMatrix: mat4,\n painter: Painter,\n isText: boolean,\n labelPlaneMatrix: mat4,\n glCoordMatrix: mat4,\n pitchWithMap: boolean,\n keepUpright: boolean,\n rotateToLine: boolean,\n projection: Projection,\n unwrappedTileID: UnwrappedTileID,\n viewportWidth: number,\n viewportHeight: number,\n translation: [number, number],\n getElevation: (x: number, y: number) => number) {\n\n const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;\n const partiallyEvaluatedSize = symbolSize.evaluateSizeForZoom(sizeData, painter.transform.zoom);\n\n const clippingBuffer: [number, number] = [256 / painter.width * 2 + 1, 256 / painter.height * 2 + 1];\n\n const dynamicLayoutVertexArray = isText ?\n bucket.text.dynamicLayoutVertexArray :\n bucket.icon.dynamicLayoutVertexArray;\n dynamicLayoutVertexArray.clear();\n\n const lineVertexArray = bucket.lineVertexArray;\n const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray;\n\n const aspectRatio = painter.transform.width / painter.transform.height;\n\n let useVertical = false;\n\n for (let s = 0; s < placedSymbols.length; s++) {\n const symbol = placedSymbols.get(s);\n\n // Don't do calculations for vertical glyphs unless the previous symbol was horizontal\n // and we determined that vertical glyphs were necessary.\n // Also don't do calculations for symbols that are collided and fully faded out\n if (symbol.hidden || symbol.writingMode === WritingMode.vertical && !useVertical) {\n hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n continue;\n }\n // Awkward... but we're counting on the paired \"vertical\" symbol coming immediately after its horizontal counterpart\n useVertical = false;\n\n const anchorPos = project(symbol.anchorX, symbol.anchorY, posMatrix, getElevation);\n\n // Don't bother calculating the correct point for invisible labels.\n if (!isVisible(anchorPos.point, clippingBuffer)) {\n hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n continue;\n }\n\n const cameraToAnchorDistance = anchorPos.signedDistanceFromCamera;\n const perspectiveRatio = getPerspectiveRatio(painter.transform.cameraToCenterDistance, cameraToAnchorDistance);\n\n const fontSize = symbolSize.evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol);\n const pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;\n\n const tileAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);\n const projectionCache: ProjectionCache = {projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false};\n\n const projectionContext: SymbolProjectionContext = {\n getElevation,\n labelPlaneMatrix,\n lineVertexArray,\n pitchWithMap,\n projectionCache,\n projection,\n tileAnchorPoint,\n unwrappedTileID,\n width: viewportWidth,\n height: viewportHeight,\n translation\n };\n\n const placeUnflipped: any = placeGlyphsAlongLine(projectionContext, symbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, glCoordMatrix,\n bucket.glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine);\n\n useVertical = placeUnflipped.useVertical;\n\n if (placeUnflipped.notEnoughRoom || useVertical ||\n (placeUnflipped.needsFlipping &&\n (placeGlyphsAlongLine(projectionContext, symbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, glCoordMatrix,\n bucket.glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine) as any).notEnoughRoom)) {\n hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n }\n }\n\n if (isText) {\n bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);\n } else {\n bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);\n }\n}\n\ntype FirstAndLastGlyphPlacement = {\n first: PlacedGlyph;\n last: PlacedGlyph;\n} | null;\n\n/*\n * Place the first and last glyph of a line label, projected to the label plane.\n * This function is called both during collision detection (to determine the label's size)\n * and during line label rendering (to make sure the label fits on the line geometry with\n * the current camera position, which may differ from the position used during collision detection).\n *\n * Calling this function has the effect of populating the \"projectionCache\" with all projected\n * vertex locations the label will need, making future calls to placeGlyphAlongLine (for all the\n * intermediate glyphs) much cheaper.\n *\n * Returns null if the label can't fit on the geometry\n */\nfunction placeFirstAndLastGlyph(\n fontScale: number,\n glyphOffsetArray: GlyphOffsetArray,\n lineOffsetX: number,\n lineOffsetY: number,\n flip: boolean,\n symbol: any,\n rotateToLine: boolean,\n projectionContext: SymbolProjectionContext): FirstAndLastGlyphPlacement {\n const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;\n const lineStartIndex = symbol.lineStartIndex;\n const lineEndIndex = symbol.lineStartIndex + symbol.lineLength;\n\n const firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex);\n const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1);\n\n const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment,\n lineStartIndex, lineEndIndex, projectionContext, rotateToLine);\n if (!firstPlacedGlyph)\n return null;\n\n const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment,\n lineStartIndex, lineEndIndex, projectionContext, rotateToLine);\n if (!lastPlacedGlyph)\n return null;\n\n if (projectionContext.projectionCache.anyProjectionOccluded) {\n return null;\n }\n\n return {first: firstPlacedGlyph, last: lastPlacedGlyph};\n}\n\nfunction requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio) {\n if (writingMode === WritingMode.horizontal) {\n // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate\n // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal\n // and vertical versions can have slightly different projections which could lead to angles where both or\n // neither showed.\n const rise = Math.abs(lastPoint.y - firstPoint.y);\n const run = Math.abs(lastPoint.x - firstPoint.x) * aspectRatio;\n if (rise > run) {\n return {useVertical: true};\n }\n }\n\n if (writingMode === WritingMode.vertical ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) {\n // Includes \"horizontalOnly\" case for labels without vertical glyphs\n return {needsFlipping: true};\n }\n\n return null;\n}\n\n/*\n* Place first and last glyph along the line projected to label plane, and if they fit\n* iterate through all the intermediate glyphs, calculating their label plane positions\n* from the projected line.\n*\n* Finally, add resulting glyph position calculations to dynamicLayoutVertexArray for\n* upload to the GPU\n*/\nfunction placeGlyphsAlongLine(projectionContext: SymbolProjectionContext, symbol, fontSize, flip, keepUpright, posMatrix, glCoordMatrix, glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine) {\n const fontScale = fontSize / 24;\n const lineOffsetX = symbol.lineOffsetX * fontScale;\n const lineOffsetY = symbol.lineOffsetY * fontScale;\n\n let placedGlyphs;\n if (symbol.numGlyphs > 1) {\n const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;\n const lineStartIndex = symbol.lineStartIndex;\n const lineEndIndex = symbol.lineStartIndex + symbol.lineLength;\n\n // Place the first and the last glyph in the label first, so we can figure out\n // the overall orientation of the label and determine whether it needs to be flipped in keepUpright mode\n const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext);\n if (!firstAndLastGlyph) {\n return {notEnoughRoom: true};\n }\n const firstPoint = project(firstAndLastGlyph.first.point.x, firstAndLastGlyph.first.point.y, glCoordMatrix, projectionContext.getElevation).point;\n const lastPoint = project(firstAndLastGlyph.last.point.x, firstAndLastGlyph.last.point.y, glCoordMatrix, projectionContext.getElevation).point;\n\n if (keepUpright && !flip) {\n const orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio);\n if (orientationChange) {\n return orientationChange;\n }\n }\n\n placedGlyphs = [firstAndLastGlyph.first];\n for (let glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) {\n // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed\n placedGlyphs.push(placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, symbol.segment,\n lineStartIndex, lineEndIndex, projectionContext, rotateToLine));\n }\n placedGlyphs.push(firstAndLastGlyph.last);\n } else {\n // Only a single glyph to place\n // So, determine whether to flip based on projected angle of the line segment it's on\n if (keepUpright && !flip) {\n const a = project(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, posMatrix, projectionContext.getElevation).point;\n const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1);\n const tileSegmentEnd = new Point(projectionContext.lineVertexArray.getx(tileVertexIndex), projectionContext.lineVertexArray.gety(tileVertexIndex));\n const projectedVertex = project(tileSegmentEnd.x, tileSegmentEnd.y, posMatrix, projectionContext.getElevation);\n // We know the anchor will be in the viewport, but the end of the line segment may be\n // behind the plane of the camera, in which case we can use a point at any arbitrary (closer)\n // point on the segment.\n const b = (projectedVertex.signedDistanceFromCamera > 0) ?\n projectedVertex.point :\n projectTruncatedLineSegmentToLabelPlane(projectionContext.tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix, projectionContext);\n\n const orientationChange = requiresOrientationChange(symbol.writingMode, a, b, aspectRatio);\n if (orientationChange) {\n return orientationChange;\n }\n }\n const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, symbol.segment,\n symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, projectionContext, rotateToLine);\n if (!singleGlyph || projectionContext.projectionCache.anyProjectionOccluded)\n return {notEnoughRoom: true};\n\n placedGlyphs = [singleGlyph];\n }\n\n for (const glyph of placedGlyphs) {\n addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle);\n }\n return {};\n}\n\n/**\n * Takes a line and direction from `previousTilePoint` to `currentTilePoint`,\n * projects it to *label plane*,\n * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`.\n * @param previousTilePoint - Line start point, in tile coordinates.\n * @param currentTilePoint - Line end point, in tile coordinates.\n * @param previousProjectedPoint - Projection of `previousTilePoint` into *label plane*.\n * @param minimumLength - Distance in the projected space along the line for the returned point.\n * @param projectionMatrix - Matrix to use during projection.\n * @param projectionContext - Projection context, used only for terrain's `getElevation`.\n */\nfunction projectTruncatedLineSegmentToLabelPlane(previousTilePoint: Point, currentTilePoint: Point, previousProjectedPoint: Point, minimumLength: number, projectionMatrix: mat4, projectionContext: SymbolProjectionContext) {\n return _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext);\n}\n\n/**\n * Takes a line and direction from `previousTilePoint` to `currentTilePoint`,\n * projects it to *viewport*,\n * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`.\n * @param previousTilePoint - Line start point, in tile coordinates.\n * @param currentTilePoint - Line end point, in tile coordinates.\n * @param previousProjectedPoint - Projection of `previousTilePoint` into *viewport*.\n * @param minimumLength - Distance in the projected space along the line for the returned point.\n * @param projectionContext - Projection context, used for terrain's `getElevation`, and either the `labelPlaneMatrix` or the map's special projection (mostly for globe).\n */\nfunction projectTruncatedLineSegmentToViewport(previousTilePoint: Point, currentTilePoint: Point, previousProjectedPoint: Point, minimumLength: number, projectionContext: SymbolProjectionContext) {\n return _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, undefined, projectionContext);\n}\n\n/**\n * Do not use directly, use {@link projectTruncatedLineSegmentToLabelPlane} or {@link projectTruncatedLineSegmentToViewport} instead,\n * depending on the target space.\n *\n * Projects a \"virtual\" vertex along a line segment.\n * If `projectionMatrix` is not undefined, does a simple projection using this matrix.\n * Otherwise, either projects to label plane using the `labelPlaneMatrix`\n * or projects to viewport using the special map projection (mostly for globe) by calling {@link projectTileCoordinatesToViewport}.\n */\nfunction _projectTruncatedLineSegment(previousTilePoint: Point, currentTilePoint: Point, previousProjectedPoint: Point, minimumLength: number, projectionMatrix: mat4 | undefined, projectionContext: SymbolProjectionContext) {\n // We are assuming \"previousTilePoint\" won't project to a point within one unit of the camera plane\n // If it did, that would mean our label extended all the way out from within the viewport to a (very distant)\n // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the\n // plane of the camera.\n const unitVertexToBeProjected = previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit());\n const projectedUnitVertex = projectionMatrix !== undefined ?\n project(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionMatrix, projectionContext.getElevation).point :\n projectTileCoordinatesToViewport(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionContext).point;\n const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex);\n return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag()));\n}\n\ntype IndexToPointCache = { [lineIndex: number]: Point };\n\n/**\n * @internal\n * We calculate label-plane projected points for line vertices as we place glyphs along the line\n * Since we will use the same vertices for potentially many glyphs, cache the results for this bucket\n * over the course of the render. Each vertex location also potentially has one offset equivalent\n * for us to hold onto. The vertex indices are per-symbol-bucket.\n */\ntype ProjectionCache = {\n /**\n * tile-unit vertices projected into label-plane units\n */\n projections: IndexToPointCache;\n /**\n * label-plane vertices which have been shifted to follow an offset line\n */\n offsets: IndexToPointCache;\n /**\n * Cached projected anchor point.\n */\n cachedAnchorPoint: Point | undefined;\n /**\n * Was any projected point occluded by the map itself (eg. occluded by the planet when using globe projection).\n *\n * Viewport-pitched line-following texts where *any* of the line points is hidden behind the planet curve becomes entirely hidden.\n * This is perhaps not the most ideal behavior, but it works, it is simple and planetary-scale texts such as this seem to be a rare edge case.\n */\n anyProjectionOccluded: boolean;\n};\n\n/**\n * @internal\n * Arguments necessary to project a vertex to the label plane\n */\nexport type SymbolProjectionContext = {\n /**\n * Used to cache results, save cost if projecting the same vertex multiple times\n */\n projectionCache: ProjectionCache;\n /**\n * The array of tile-unit vertices transferred from worker\n */\n lineVertexArray: SymbolLineVertexArray;\n /**\n * Label plane projection matrix\n */\n labelPlaneMatrix: mat4;\n /**\n * Function to get elevation at a point\n * @param x - the x coordinate\n * @param y - the y coordinate\n */\n getElevation: (x: number, y: number) => number;\n /**\n * Only for creating synthetic vertices if vertex would otherwise project behind plane of camera,\n * but still convenient to pass it inside this type.\n */\n tileAnchorPoint: Point;\n /**\n * True when line glyphs are projected onto the map, instead of onto the viewport.\n */\n pitchWithMap: boolean;\n projection: Projection;\n unwrappedTileID: UnwrappedTileID;\n /**\n * Viewport width.\n */\n width: number;\n /**\n * Viewport height.\n */\n height: number;\n /**\n * Translation in tile units, computed using text-translate and text-translate-anchor paint style properties.\n */\n translation: [number, number];\n};\n\n/**\n * Only for creating synthetic vertices if vertex would otherwise project behind plane of camera\n */\nexport type ProjectionSyntheticVertexArgs = {\n distanceFromAnchor: number;\n previousVertex: Point;\n direction: number;\n absOffsetX: number;\n};\n\n/**\n * Transform a vertex from tile coordinates to label plane coordinates\n * @param index - index of vertex to project\n * @param projectionContext - necessary data to project a vertex\n * @returns the vertex projected to the label plane\n */\nfunction projectLineVertexToViewport(index: number, projectionContext: SymbolProjectionContext, syntheticVertexArgs: ProjectionSyntheticVertexArgs): Point {\n const cache = projectionContext.projectionCache;\n\n if (cache.projections[index]) {\n return cache.projections[index];\n }\n const currentVertex = new Point(\n projectionContext.lineVertexArray.getx(index),\n projectionContext.lineVertexArray.gety(index));\n\n const projection = projectTileCoordinatesToViewport(currentVertex.x, currentVertex.y, projectionContext);\n\n if (projection.signedDistanceFromCamera > 0) {\n cache.projections[index] = projection.point;\n cache.anyProjectionOccluded = cache.anyProjectionOccluded || projection.isOccluded;\n return projection.point;\n }\n\n // The vertex is behind the plane of the camera, so we can't project it\n // Instead, we'll create a vertex along the line that's far enough to include the glyph\n const previousLineVertexIndex = index - syntheticVertexArgs.direction;\n const previousTilePoint = syntheticVertexArgs.distanceFromAnchor === 0 ?\n projectionContext.tileAnchorPoint :\n new Point(projectionContext.lineVertexArray.getx(previousLineVertexIndex), projectionContext.lineVertexArray.gety(previousLineVertexIndex));\n\n // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment\n const minimumLength = syntheticVertexArgs.absOffsetX - syntheticVertexArgs.distanceFromAnchor + 1;\n return projectTruncatedLineSegmentToViewport(previousTilePoint, currentVertex, syntheticVertexArgs.previousVertex, minimumLength, projectionContext);\n}\n\nfunction projectTileCoordinatesToViewport(x: number, y: number, projectionContext: SymbolProjectionContext): PointProjection {\n const translatedX = x + projectionContext.translation[0];\n const translatedY = y + projectionContext.translation[1];\n let projection;\n if (!projectionContext.pitchWithMap && projectionContext.projection.useSpecialProjectionForSymbols) {\n projection = projectionContext.projection.projectTileCoordinates(translatedX, translatedY, projectionContext.unwrappedTileID, projectionContext.getElevation);\n projection.point.x = (projection.point.x * 0.5 + 0.5) * projectionContext.width;\n projection.point.y = (-projection.point.y * 0.5 + 0.5) * projectionContext.height;\n } else {\n projection = project(translatedX, translatedY, projectionContext.labelPlaneMatrix, projectionContext.getElevation);\n projection.isOccluded = false;\n }\n return projection;\n}\n\n/**\n * Calculate the normal vector for a line segment\n * @param segmentVector - will be mutated as a tiny optimization\n * @param offset - magnitude of resulting vector\n * @param direction - direction of line traversal\n * @returns a normal vector from the segment, with magnitude equal to offset amount\n */\nfunction transformToOffsetNormal(segmentVector: Point, offset: number, direction: number): Point {\n return segmentVector._unit()._perp()._mult(offset * direction);\n}\n\n/**\n * Construct offset line segments for the current segment and the next segment, then extend/shrink\n * the segments until they intersect. If the segments are parallel, then they will touch with no modification.\n *\n * @param index - Index of the current vertex\n * @param prevToCurrentOffsetNormal - Normal vector of the line segment from the previous vertex to the current vertex\n * @param currentVertex - Current (non-offset) vertex projected to the label plane\n * @param lineStartIndex - Beginning index for the line this label is on\n * @param lineEndIndex - End index for the line this label is on\n * @param offsetPreviousVertex - The previous vertex projected to the label plane, and then offset along the previous segments normal\n * @param lineOffsetY - Magnitude of the offset\n * @param projectionContext - Necessary data for tile-to-label-plane projection\n * @returns The point at which the current and next line segments intersect, once offset and extended/shrunk to their meeting point\n */\nfunction findOffsetIntersectionPoint(\n index: number,\n prevToCurrentOffsetNormal: Point,\n currentVertex: Point,\n lineStartIndex: number,\n lineEndIndex: number,\n offsetPreviousVertex: Point,\n lineOffsetY: number,\n projectionContext: SymbolProjectionContext,\n syntheticVertexArgs: ProjectionSyntheticVertexArgs) {\n if (projectionContext.projectionCache.offsets[index]) {\n return projectionContext.projectionCache.offsets[index];\n }\n\n const offsetCurrentVertex = currentVertex.add(prevToCurrentOffsetNormal);\n\n if (index + syntheticVertexArgs.direction < lineStartIndex || index + syntheticVertexArgs.direction >= lineEndIndex) {\n // This is the end of the line, no intersection to calculate\n projectionContext.projectionCache.offsets[index] = offsetCurrentVertex;\n return offsetCurrentVertex;\n }\n // Offset the vertices for the next segment\n const nextVertex = projectLineVertexToViewport(index + syntheticVertexArgs.direction, projectionContext, syntheticVertexArgs);\n const currentToNextOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, syntheticVertexArgs.direction);\n const offsetNextSegmentBegin = currentVertex.add(currentToNextOffsetNormal);\n const offsetNextSegmentEnd = nextVertex.add(currentToNextOffsetNormal);\n\n // find the intersection of these two lines\n // if the lines are parallel, offsetCurrent/offsetNextBegin will touch\n projectionContext.projectionCache.offsets[index] = findLineIntersection(offsetPreviousVertex, offsetCurrentVertex, offsetNextSegmentBegin, offsetNextSegmentEnd) || offsetCurrentVertex;\n\n return projectionContext.projectionCache.offsets[index];\n}\n\n/**\n * Placed Glyph type\n */\ntype PlacedGlyph = {\n /**\n * The point at which the glyph should be placed, in label plane coordinates\n */\n point: Point;\n /**\n * The angle at which the glyph should be placed\n */\n angle: number;\n /**\n * The label-plane path used to reach this glyph: used only for collision detection\n */\n path: Array;\n};\n\n/*\n * Place a single glyph along its line, projected into the label plane, by iterating outward\n * from the anchor point until the distance traversed in the label plane equals the glyph's\n * offsetX. Returns null if the glyph can't fit on the line geometry.\n */\nfunction placeGlyphAlongLine(\n offsetX: number,\n lineOffsetX: number,\n lineOffsetY: number,\n flip: boolean,\n anchorSegment: number,\n lineStartIndex: number,\n lineEndIndex: number,\n projectionContext: SymbolProjectionContext,\n rotateToLine: boolean): PlacedGlyph | null {\n\n const combinedOffsetX = flip ?\n offsetX - lineOffsetX :\n offsetX + lineOffsetX;\n\n let direction = combinedOffsetX > 0 ? 1 : -1;\n\n let angle = 0;\n if (flip) {\n // The label needs to be flipped to keep text upright.\n // Iterate in the reverse direction.\n direction *= -1;\n angle = Math.PI;\n }\n\n if (direction < 0) angle += Math.PI;\n\n let currentIndex = direction > 0 ?\n lineStartIndex + anchorSegment :\n lineStartIndex + anchorSegment + 1;\n\n // Project anchor point to proper label plane and cache it\n let anchorPoint: Point;\n\n if (projectionContext.projectionCache.cachedAnchorPoint) {\n anchorPoint = projectionContext.projectionCache.cachedAnchorPoint;\n } else {\n anchorPoint = projectTileCoordinatesToViewport(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, projectionContext).point;\n projectionContext.projectionCache.cachedAnchorPoint = anchorPoint;\n }\n\n let currentVertex = anchorPoint;\n let previousVertex = anchorPoint;\n\n // offsetPrev and intersectionPoint are analogous to previousVertex and currentVertex\n // but if there's a line offset they are calculated in parallel as projection happens\n let offsetIntersectionPoint: Point;\n let offsetPreviousVertex: Point;\n\n let distanceFromAnchor = 0;\n let currentSegmentDistance = 0;\n const absOffsetX = Math.abs(combinedOffsetX);\n const pathVertices: Array = [];\n\n let currentLineSegment: Point;\n while (distanceFromAnchor + currentSegmentDistance <= absOffsetX) {\n currentIndex += direction;\n\n // offset does not fit on the projected line\n if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex)\n return null;\n\n // accumulate values from last iteration\n distanceFromAnchor += currentSegmentDistance;\n previousVertex = currentVertex;\n offsetPreviousVertex = offsetIntersectionPoint;\n\n const syntheticVertexArgs: ProjectionSyntheticVertexArgs = {\n absOffsetX,\n direction,\n distanceFromAnchor,\n previousVertex\n };\n\n // find next vertex in viewport space\n currentVertex = projectLineVertexToViewport(currentIndex, projectionContext, syntheticVertexArgs);\n if (lineOffsetY === 0) {\n // Store vertices for collision detection and update current segment geometry\n pathVertices.push(previousVertex);\n currentLineSegment = currentVertex.sub(previousVertex);\n } else {\n // Calculate the offset for this section\n let prevToCurrentOffsetNormal;\n const prevToCurrent = currentVertex.sub(previousVertex);\n if (prevToCurrent.mag() === 0) {\n // We are starting with our anchor point directly on the vertex, so look one vertex ahead\n // to calculate a normal\n const nextVertex = projectLineVertexToViewport(currentIndex + direction, projectionContext, syntheticVertexArgs);\n prevToCurrentOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, direction);\n } else {\n prevToCurrentOffsetNormal = transformToOffsetNormal(prevToCurrent, lineOffsetY, direction);\n }\n // Initialize offsetPrev on our first iteration, after that it will be pre-calculated\n if (!offsetPreviousVertex)\n offsetPreviousVertex = previousVertex.add(prevToCurrentOffsetNormal);\n\n offsetIntersectionPoint = findOffsetIntersectionPoint(currentIndex, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs);\n\n pathVertices.push(offsetPreviousVertex);\n currentLineSegment = offsetIntersectionPoint.sub(offsetPreviousVertex);\n }\n currentSegmentDistance = currentLineSegment.mag();\n }\n\n // The point is on the current segment. Interpolate to find it.\n const segmentInterpolationT = (absOffsetX - distanceFromAnchor) / currentSegmentDistance;\n const p = currentLineSegment._mult(segmentInterpolationT)._add(offsetPreviousVertex || previousVertex);\n\n const segmentAngle = angle + Math.atan2(currentVertex.y - previousVertex.y, currentVertex.x - previousVertex.x);\n\n pathVertices.push(p);\n\n return {\n point: p,\n angle: rotateToLine ? segmentAngle : 0.0,\n path: pathVertices\n };\n}\n\nconst hiddenGlyphAttributes = new Float32Array([-Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0]);\n\n// Hide them by moving them offscreen. We still need to add them to the buffer\n// because the dynamic buffer is paired with a static buffer that doesn't get updated.\nfunction hideGlyphs(num: number, dynamicLayoutVertexArray: SymbolDynamicLayoutArray) {\n for (let i = 0; i < num; i++) {\n const offset = dynamicLayoutVertexArray.length;\n dynamicLayoutVertexArray.resize(offset + 4);\n // Since all hidden glyphs have the same attributes, we can build up the array faster with a single call to Float32Array.set\n // for each set of four vertices, instead of calling addDynamicAttributes for each vertex.\n dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3);\n }\n}\n\n// For line label layout, we're not using z output and our w input is always 1\n// This custom matrix transformation ignores those components to make projection faster\nfunction xyTransformMat4(out: vec4, a: vec4, m: mat4) {\n const x = a[0], y = a[1];\n out[0] = m[0] * x + m[4] * y + m[12];\n out[1] = m[1] * x + m[5] * y + m[13];\n out[3] = m[3] * x + m[7] * y + m[15];\n return out;\n}\n","import Point from '@mapbox/point-geometry';\nimport {clipLine} from './clip_line';\nimport {PathInterpolator} from './path_interpolator';\n\nimport * as intersectionTests from '../util/intersection_tests';\nimport {GridIndex} from './grid_index';\nimport {mat4, vec4} from 'gl-matrix';\nimport ONE_EM from '../symbol/one_em';\n\nimport * as projection from '../symbol/projection';\n\nimport type {Transform} from '../geo/transform';\nimport type {SingleCollisionBox} from '../data/bucket/symbol_bucket';\nimport type {\n GlyphOffsetArray,\n SymbolLineVertexArray\n} from '../data/array_types.g';\nimport type {OverlapMode} from '../style/style_layer/overlap_mode';\nimport {UnwrappedTileID} from '../source/tile_id';\nimport {SymbolProjectionContext} from '../symbol/projection';\nimport {Projection} from '../geo/projection/projection';\nimport {clamp, getAABB} from '../util/util';\n\n// When a symbol crosses the edge that causes it to be included in\n// collision detection, it will cause changes in the symbols around\n// it. This constant specifies how many pixels to pad the edge of\n// the viewport for collision detection so that the bulk of the changes\n// occur offscreen. Making this constant greater increases label\n// stability, but it's expensive.\nexport const viewportPadding = 100;\n\nexport type PlacedCircles = {\n circles: Array;\n offscreen: boolean;\n collisionDetected: boolean;\n};\n\nexport type PlacedBox = {\n box: Array;\n placeable: boolean;\n offscreen: boolean;\n};\n\nexport type FeatureKey = {\n bucketInstanceId: number;\n featureIndex: number;\n collisionGroupID: number;\n overlapMode: OverlapMode;\n};\n\ntype ProjectedBox = {\n /**\n * The AABB in the format [minX, minY, maxX, maxY].\n */\n box: [number, number, number, number];\n allPointsOccluded: boolean;\n};\n\n/**\n * @internal\n * A collision index used to prevent symbols from overlapping. It keep tracks of\n * where previous symbols have been placed and is used to check if a new\n * symbol overlaps with any previously added symbols.\n *\n * There are two steps to insertion: first placeCollisionBox/Circles checks if\n * there's room for a symbol, then insertCollisionBox/Circles actually puts the\n * symbol in the index. The two step process allows paired symbols to be inserted\n * together even if they overlap.\n */\nexport class CollisionIndex {\n grid: GridIndex;\n ignoredGrid: GridIndex;\n transform: Transform;\n pitchFactor: number;\n screenRightBoundary: number;\n screenBottomBoundary: number;\n gridRightBoundary: number;\n gridBottomBoundary: number;\n mapProjection: Projection;\n\n // With perspectiveRatio the fontsize is calculated for tilted maps (near = bigger, far = smaller).\n // The cutoff defines a threshold to no longer render labels near the horizon.\n perspectiveRatioCutoff: number;\n\n constructor(\n transform: Transform,\n projection: Projection,\n grid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25),\n ignoredGrid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)\n ) {\n this.transform = transform;\n this.mapProjection = projection;\n\n this.grid = grid;\n this.ignoredGrid = ignoredGrid;\n this.pitchFactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance;\n\n this.screenRightBoundary = transform.width + viewportPadding;\n this.screenBottomBoundary = transform.height + viewportPadding;\n this.gridRightBoundary = transform.width + 2 * viewportPadding;\n this.gridBottomBoundary = transform.height + 2 * viewportPadding;\n\n this.perspectiveRatioCutoff = 0.6;\n }\n\n placeCollisionBox(\n collisionBox: SingleCollisionBox,\n overlapMode: OverlapMode,\n textPixelRatio: number,\n posMatrix: mat4,\n unwrappedTileID: UnwrappedTileID,\n pitchWithMap: boolean,\n rotateWithMap: boolean,\n translation: [number, number],\n collisionGroupPredicate?: (key: FeatureKey) => boolean,\n getElevation?: (x: number, y: number) => number,\n shift?: Point\n ): PlacedBox {\n const x = collisionBox.anchorPointX + translation[0];\n const y = collisionBox.anchorPointY + translation[1];\n const projectedPoint = this.projectAndGetPerspectiveRatio(\n posMatrix,\n x,\n y,\n unwrappedTileID,\n getElevation\n );\n\n const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;\n\n let projectedBox: ProjectedBox;\n\n if (!pitchWithMap && !rotateWithMap) {\n // Fast path for common symbols\n const pointX = projectedPoint.point.x + (shift ? shift.x * tileToViewport : 0);\n const pointY = projectedPoint.point.y + (shift ? shift.y * tileToViewport : 0);\n projectedBox = {\n allPointsOccluded: false,\n box: [\n pointX + collisionBox.x1 * tileToViewport,\n pointY + collisionBox.y1 * tileToViewport,\n pointX + collisionBox.x2 * tileToViewport,\n pointY + collisionBox.y2 * tileToViewport,\n ]\n };\n } else {\n projectedBox = this._projectCollisionBox(\n collisionBox,\n tileToViewport,\n posMatrix,\n unwrappedTileID,\n pitchWithMap,\n rotateWithMap,\n translation,\n projectedPoint,\n getElevation,\n shift\n );\n }\n\n const [tlX, tlY, brX, brY] = projectedBox.box;\n\n const projectionOccluded = this.mapProjection.useSpecialProjectionForSymbols ? (pitchWithMap ? projectedBox.allPointsOccluded : this.mapProjection.isOccluded(x, y, unwrappedTileID)) : false;\n\n if (projectionOccluded || projectedPoint.perspectiveRatio < this.perspectiveRatioCutoff || !this.isInsideGrid(tlX, tlY, brX, brY) ||\n (overlapMode !== 'always' && this.grid.hitTest(tlX, tlY, brX, brY, overlapMode, collisionGroupPredicate))) {\n return {\n box: [tlX, tlY, brX, brY],\n placeable: false,\n offscreen: false\n };\n }\n\n return {\n box: [tlX, tlY, brX, brY],\n placeable: true,\n offscreen: this.isOffscreen(tlX, tlY, brX, brY)\n };\n }\n\n placeCollisionCircles(\n overlapMode: OverlapMode,\n symbol: any,\n lineVertexArray: SymbolLineVertexArray,\n glyphOffsetArray: GlyphOffsetArray,\n fontSize: number,\n posMatrix: mat4,\n unwrappedTileID: UnwrappedTileID,\n labelPlaneMatrix: mat4,\n labelToScreenMatrix: mat4,\n showCollisionCircles: boolean,\n pitchWithMap: boolean,\n collisionGroupPredicate: (key: FeatureKey) => boolean,\n circlePixelDiameter: number,\n textPixelPadding: number,\n translation: [number, number],\n getElevation: (x: number, y: number) => number\n ): PlacedCircles {\n const placedCollisionCircles = [];\n\n const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);\n const perspectiveRatio = this.getPerspectiveRatio(posMatrix, tileUnitAnchorPoint.x, tileUnitAnchorPoint.y, unwrappedTileID, getElevation);\n const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;\n const labelPlaneFontScale = labelPlaneFontSize / ONE_EM;\n\n const projectionCache = {projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false};\n const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;\n const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;\n\n const projectionContext: SymbolProjectionContext = {\n getElevation,\n labelPlaneMatrix,\n lineVertexArray,\n pitchWithMap,\n projectionCache,\n projection: this.mapProjection,\n tileAnchorPoint: tileUnitAnchorPoint,\n unwrappedTileID,\n width: this.transform.width,\n height: this.transform.height,\n translation\n };\n\n const firstAndLastGlyph = projection.placeFirstAndLastGlyph(\n labelPlaneFontScale,\n glyphOffsetArray,\n lineOffsetX,\n lineOffsetY,\n /*flip*/ false,\n symbol,\n false,\n projectionContext);\n\n let collisionDetected = false;\n let inGrid = false;\n let entirelyOffscreen = true;\n\n if (firstAndLastGlyph) {\n const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding;\n const screenPlaneMin = new Point(-viewportPadding, -viewportPadding);\n const screenPlaneMax = new Point(this.screenRightBoundary, this.screenBottomBoundary);\n const interpolator = new PathInterpolator();\n\n // Construct a projected path from projected line vertices. Anchor points are ignored and removed\n const first = firstAndLastGlyph.first;\n const last = firstAndLastGlyph.last;\n\n let projectedPath: Array = [];\n for (let i = first.path.length - 1; i >= 1; i--) {\n projectedPath.push(first.path[i]);\n }\n for (let i = 1; i < last.path.length; i++) {\n projectedPath.push(last.path[i]);\n }\n\n // Tolerate a slightly longer distance than one diameter between two adjacent circles\n const circleDist = radius * 2.5;\n\n // The path might need to be converted into screen space if a pitched map is used as the label space\n if (labelToScreenMatrix) {\n const screenSpacePath = this.projectPathToScreenSpace(projectedPath, projectionContext, labelToScreenMatrix);\n // Do not try to place collision circles if even one of the points is behind the camera.\n // This is a plausible scenario with big camera pitch angles\n if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) {\n projectedPath = [];\n } else {\n projectedPath = screenSpacePath.map(p => p.point);\n }\n }\n\n let segments = [];\n\n if (projectedPath.length > 0) {\n // Quickly check if the path is fully inside or outside of the padded collision region.\n // For overlapping paths we'll only create collision circles for the visible segments\n const minPoint = projectedPath[0].clone();\n const maxPoint = projectedPath[0].clone();\n\n for (let i = 1; i < projectedPath.length; i++) {\n minPoint.x = Math.min(minPoint.x, projectedPath[i].x);\n minPoint.y = Math.min(minPoint.y, projectedPath[i].y);\n maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x);\n maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y);\n }\n\n if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x &&\n minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) {\n // Quad fully visible\n segments = [projectedPath];\n } else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x ||\n maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) {\n // Not visible\n segments = [];\n } else {\n segments = clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y);\n }\n }\n\n for (const seg of segments) {\n // interpolate positions for collision circles. Add a small padding to both ends of the segment\n interpolator.reset(seg, radius * 0.25);\n\n let numCircles = 0;\n\n if (interpolator.length <= 0.5 * radius) {\n numCircles = 1;\n } else {\n numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1;\n }\n\n for (let i = 0; i < numCircles; i++) {\n const t = i / Math.max(numCircles - 1, 1);\n const circlePosition = interpolator.lerp(t);\n\n // add viewport padding to the position and perform initial collision check\n const centerX = circlePosition.x + viewportPadding;\n const centerY = circlePosition.y + viewportPadding;\n\n placedCollisionCircles.push(centerX, centerY, radius, 0);\n\n const x1 = centerX - radius;\n const y1 = centerY - radius;\n const x2 = centerX + radius;\n const y2 = centerY + radius;\n\n entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2);\n inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2);\n\n if (overlapMode !== 'always' && this.grid.hitTestCircle(centerX, centerY, radius, overlapMode, collisionGroupPredicate)) {\n // Don't early exit if we're showing the debug circles because we still want to calculate\n // which circles are in use\n collisionDetected = true;\n if (!showCollisionCircles) {\n return {\n circles: [],\n offscreen: false,\n collisionDetected\n };\n }\n }\n }\n }\n }\n\n return {\n circles: ((!showCollisionCircles && collisionDetected) || !inGrid || perspectiveRatio < this.perspectiveRatioCutoff) ? [] : placedCollisionCircles,\n offscreen: entirelyOffscreen,\n collisionDetected\n };\n }\n\n projectPathToScreenSpace(projectedPath: Array, projectionContext: SymbolProjectionContext, labelToScreenMatrix: mat4) {\n return projectedPath.map(p => projection.project(p.x, p.y, labelToScreenMatrix, projectionContext.getElevation));\n }\n\n /**\n * Because the geometries in the CollisionIndex are an approximation of the shape of\n * symbols on the map, we use the CollisionIndex to look up the symbol part of\n * `queryRenderedFeatures`.\n */\n queryRenderedSymbols(viewportQueryGeometry: Array) {\n if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) {\n return {};\n }\n\n const query = [];\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const point of viewportQueryGeometry) {\n const gridPoint = new Point(point.x + viewportPadding, point.y + viewportPadding);\n minX = Math.min(minX, gridPoint.x);\n minY = Math.min(minY, gridPoint.y);\n maxX = Math.max(maxX, gridPoint.x);\n maxY = Math.max(maxY, gridPoint.y);\n query.push(gridPoint);\n }\n\n const features = this.grid.query(minX, minY, maxX, maxY)\n .concat(this.ignoredGrid.query(minX, minY, maxX, maxY));\n\n const seenFeatures = {};\n const result = {};\n\n for (const feature of features) {\n const featureKey = feature.key;\n // Skip already seen features.\n if (seenFeatures[featureKey.bucketInstanceId] === undefined) {\n seenFeatures[featureKey.bucketInstanceId] = {};\n }\n if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) {\n continue;\n }\n\n // Check if query intersects with the feature box\n // \"Collision Circles\" for line labels are treated as boxes here\n // Since there's no actual collision taking place, the circle vs. square\n // distinction doesn't matter as much, and box geometry is easier\n // to work with.\n const bbox = [\n new Point(feature.x1, feature.y1),\n new Point(feature.x2, feature.y1),\n new Point(feature.x2, feature.y2),\n new Point(feature.x1, feature.y2)\n ];\n if (!intersectionTests.polygonIntersectsPolygon(query, bbox)) {\n continue;\n }\n\n seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true;\n if (result[featureKey.bucketInstanceId] === undefined) {\n result[featureKey.bucketInstanceId] = [];\n }\n result[featureKey.bucketInstanceId].push(featureKey.featureIndex);\n }\n\n return result;\n }\n\n insertCollisionBox(collisionBox: Array, overlapMode: OverlapMode, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {\n const grid = ignorePlacement ? this.ignoredGrid : this.grid;\n\n const key = {bucketInstanceId, featureIndex, collisionGroupID, overlapMode};\n grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]);\n }\n\n insertCollisionCircles(collisionCircles: Array, overlapMode: OverlapMode, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {\n const grid = ignorePlacement ? this.ignoredGrid : this.grid;\n\n const key = {bucketInstanceId, featureIndex, collisionGroupID, overlapMode};\n for (let k = 0; k < collisionCircles.length; k += 4) {\n grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]);\n }\n }\n\n projectAndGetPerspectiveRatio(posMatrix: mat4, x: number, y: number, _unwrappedTileID: UnwrappedTileID, getElevation?: (x: number, y: number) => number) {\n // The code here is duplicated from \"projection.ts\" for performance.\n // Code here is subject to change once globe is merged.\n let pos;\n if (getElevation) { // slow because of handle z-index\n pos = [x, y, getElevation(x, y), 1] as vec4;\n vec4.transformMat4(pos, pos, posMatrix);\n } else { // fast because of ignore z-index\n pos = [x, y, 0, 1] as vec4;\n projection.xyTransformMat4(pos, pos, posMatrix);\n }\n const w = pos[3];\n return {\n point: new Point(\n (((pos[0] / w + 1) / 2) * this.transform.width) + viewportPadding,\n (((-pos[1] / w + 1) / 2) * this.transform.height) + viewportPadding\n ),\n // See perspective ratio comment in symbol_sdf.vertex\n // We're doing collision detection in viewport space so we need\n // to scale down boxes in the distance\n perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / w),\n isOccluded: false,\n signedDistanceFromCamera: w\n };\n }\n\n getPerspectiveRatio(posMatrix: mat4, x: number, y: number, unwrappedTileID: UnwrappedTileID, getElevation?: (x: number, y: number) => number): number {\n // We don't care about the actual projected point, just its W component.\n const projected = this.mapProjection.useSpecialProjectionForSymbols ?\n this.mapProjection.projectTileCoordinates(x, y, unwrappedTileID, getElevation) :\n projection.project(x, y, posMatrix, getElevation);\n return 0.5 + 0.5 * (this.transform.cameraToCenterDistance / projected.signedDistanceFromCamera);\n }\n\n isOffscreen(x1: number, y1: number, x2: number, y2: number) {\n return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary;\n }\n\n isInsideGrid(x1: number, y1: number, x2: number, y2: number) {\n return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary;\n }\n\n /*\n * Returns a matrix for transforming collision shapes to viewport coordinate space.\n * Use this function to render e.g. collision circles on the screen.\n * example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos\n */\n getViewportMatrix() {\n const m = mat4.identity([] as any);\n mat4.translate(m, m, [-viewportPadding, -viewportPadding, 0.0]);\n return m;\n }\n\n /**\n * Applies all layout+paint properties of the given box in order to find as good approximation of its screen-space bounding box as possible.\n */\n private _projectCollisionBox(\n collisionBox: SingleCollisionBox,\n tileToViewport: number,\n posMatrix: mat4,\n unwrappedTileID: UnwrappedTileID,\n pitchWithMap: boolean,\n rotateWithMap: boolean,\n translation: [number, number],\n projectedPoint: {point: Point; perspectiveRatio: number; signedDistanceFromCamera: number},\n getElevation?: (x: number, y: number) => number,\n shift?: Point\n ): ProjectedBox {\n\n // These vectors are valid both for screen space viewport-rotation-aligned texts and for pitch-align: map texts that are map-rotation-aligned.\n let vecEast = new Point(1, 0);\n let vecSouth = new Point(0, 1);\n\n const translatedAnchor = new Point(collisionBox.anchorPointX + translation[0], collisionBox.anchorPointY + translation[1]);\n\n if (rotateWithMap && !pitchWithMap) {\n // Handles screen space texts that are always aligned east-west.\n const projectedEast = this.projectAndGetPerspectiveRatio(\n posMatrix,\n translatedAnchor.x + 1,\n translatedAnchor.y,\n unwrappedTileID,\n getElevation\n ).point;\n const toEast = projectedEast.sub(projectedPoint.point).unit();\n const angle = Math.atan(toEast.y / toEast.x) + (toEast.x < 0 ? Math.PI : 0);\n const sin = Math.sin(angle);\n const cos = Math.cos(angle);\n vecEast = new Point(cos, sin);\n vecSouth = new Point(-sin, cos);\n } else if (!rotateWithMap && pitchWithMap) {\n // Handles pitch-align: map texts that are always aligned with the viewport's X axis.\n const angle = -this.transform.angle;\n const sin = Math.sin(angle);\n const cos = Math.cos(angle);\n vecEast = new Point(cos, sin);\n vecSouth = new Point(-sin, cos);\n }\n\n // Configuration for screen space offsets\n let basePoint = projectedPoint.point;\n let distanceMultiplier = tileToViewport;\n\n if (pitchWithMap) {\n // Configuration for tile space (map-pitch-aligned) offsets\n basePoint = translatedAnchor;\n\n const zoomFraction = this.transform.zoom - Math.floor(this.transform.zoom);\n distanceMultiplier = Math.pow(2, -zoomFraction);\n distanceMultiplier *= this.mapProjection.getPitchedTextCorrection(this.transform, translatedAnchor, unwrappedTileID);\n\n // This next correction can't be applied when variable anchors are in use.\n if (!shift) {\n // Shader applies a perspective size correction, we need to apply the same correction.\n // For non-pitchWithMap texts, this is handled above by multiplying `textPixelRatio` with `projectedPoint.perspectiveRatio`,\n // which is equivalent to the non-pitchWithMap branch of the GLSL code.\n // Here, we compute and apply the pitchWithMap branch.\n // See the computation of `perspective_ratio` in the symbol vertex shaders for the GLSL code.\n const distanceRatio = projectedPoint.signedDistanceFromCamera / this.transform.cameraToCenterDistance;\n const perspectiveRatio = clamp(0.5 + 0.5 * distanceRatio, 0.0, 4.0); // Same clamp as what is used in the shader.\n distanceMultiplier *= perspectiveRatio;\n }\n }\n\n if (shift) {\n // Variable anchors are in use\n basePoint = basePoint.add(vecEast.mult(shift.x * distanceMultiplier)).add(vecSouth.mult(shift.y * distanceMultiplier));\n }\n\n const offsetXmin = collisionBox.x1 * distanceMultiplier;\n const offsetXmax = collisionBox.x2 * distanceMultiplier;\n const offsetXhalf = (offsetXmin + offsetXmax) / 2;\n const offsetYmin = collisionBox.y1 * distanceMultiplier;\n const offsetYmax = collisionBox.y2 * distanceMultiplier;\n const offsetYhalf = (offsetYmin + offsetYmax) / 2;\n\n // 0--1--2\n // | |\n // 7 3\n // | |\n // 6--5--4\n const offsetsArray: Array<{offsetX: number; offsetY: number}> = [\n {offsetX: offsetXmin, offsetY: offsetYmin},\n {offsetX: offsetXhalf, offsetY: offsetYmin},\n {offsetX: offsetXmax, offsetY: offsetYmin},\n {offsetX: offsetXmax, offsetY: offsetYhalf},\n {offsetX: offsetXmax, offsetY: offsetYmax},\n {offsetX: offsetXhalf, offsetY: offsetYmax},\n {offsetX: offsetXmin, offsetY: offsetYmax},\n {offsetX: offsetXmin, offsetY: offsetYhalf}\n ];\n\n let points: Array = [];\n\n for (const {offsetX, offsetY} of offsetsArray) {\n points.push(new Point(\n basePoint.x + vecEast.x * offsetX + vecSouth.x * offsetY,\n basePoint.y + vecEast.y * offsetX + vecSouth.y * offsetY\n ));\n }\n\n // Is any point of the collision shape visible on the globe (on beyond horizon)?\n let anyPointVisible = false;\n\n if (pitchWithMap) {\n const projected = points.map(p => this.projectAndGetPerspectiveRatio(posMatrix, p.x, p.y, unwrappedTileID, getElevation));\n\n // Is at least one of the projected points NOT behind the horizon?\n anyPointVisible = projected.some(p => !p.isOccluded);\n\n points = projected.map(p => p.point);\n } else {\n // Labels that are not pitchWithMap cannot ever hide behind the horizon.\n anyPointVisible = true;\n }\n\n return {\n box: getAABB(points),\n allPointsOccluded: !anyPointVisible\n };\n }\n}\n","import Point from '@mapbox/point-geometry';\n\n/**\n * Returns the part of a multiline that intersects with the provided rectangular box.\n *\n * @param lines - the lines to check\n * @param x1 - the left edge of the box\n * @param y1 - the top edge of the box\n * @param x2 - the right edge of the box\n * @param y2 - the bottom edge of the box\n * @returns lines\n */\nexport function clipLine(lines: Array>, x1: number, y1: number, x2: number, y2: number): Array> {\n const clippedLines = [];\n\n for (let l = 0; l < lines.length; l++) {\n const line = lines[l];\n let clippedLine;\n\n for (let i = 0; i < line.length - 1; i++) {\n let p0 = line[i];\n let p1 = line[i + 1];\n\n if (p0.x < x1 && p1.x < x1) {\n continue;\n } else if (p0.x < x1) {\n p0 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();\n } else if (p1.x < x1) {\n p1 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();\n }\n\n if (p0.y < y1 && p1.y < y1) {\n continue;\n } else if (p0.y < y1) {\n p0 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();\n } else if (p1.y < y1) {\n p1 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();\n }\n\n if (p0.x >= x2 && p1.x >= x2) {\n continue;\n } else if (p0.x >= x2) {\n p0 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();\n } else if (p1.x >= x2) {\n p1 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();\n }\n\n if (p0.y >= y2 && p1.y >= y2) {\n continue;\n } else if (p0.y >= y2) {\n p0 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();\n } else if (p1.y >= y2) {\n p1 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();\n }\n\n if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) {\n clippedLine = [p0];\n clippedLines.push(clippedLine);\n }\n\n clippedLine.push(p1);\n }\n }\n\n return clippedLines;\n}\n","import Point from '@mapbox/point-geometry';\n\nimport {register} from '../util/web_worker_transfer';\n\nexport class Anchor extends Point {\n angle: any;\n segment?: number;\n\n constructor(x: number, y: number, angle: number, segment?: number) {\n super(x, y);\n this.angle = angle;\n if (segment !== undefined) {\n this.segment = segment;\n }\n }\n\n clone() {\n return new Anchor(this.x, this.y, this.angle, this.segment);\n }\n}\n\nregister('Anchor', Anchor);\n","import {VariableAnchorOffsetCollection, VariableAnchorOffsetCollectionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {SymbolFeature} from '../../data/bucket/symbol_bucket';\nimport {CanonicalTileID} from '../../source/tile_id';\nimport ONE_EM from '../../symbol/one_em';\nimport {SymbolStyleLayer} from './symbol_style_layer';\n\nexport enum TextAnchorEnum {\n 'center' = 1,\n 'left' = 2,\n 'right' = 3,\n 'top' = 4,\n 'bottom' = 5,\n 'top-left' = 6,\n 'top-right' = 7,\n 'bottom-left' = 8,\n 'bottom-right' = 9\n}\n\nexport type TextAnchor = keyof typeof TextAnchorEnum;\n\n// The radial offset is to the edge of the text box\n// In the horizontal direction, the edge of the text box is where glyphs start\n// But in the vertical direction, the glyphs appear to \"start\" at the baseline\n// We don't actually load baseline data, but we assume an offset of ONE_EM - 17\n// (see \"yOffset\" in shaping.js)\nconst baselineOffset = 7;\nexport const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY;\n\nexport function evaluateVariableOffset(anchor: TextAnchor, offset: [number, number]): [number, number] {\n\n function fromRadialOffset(anchor: TextAnchor, radialOffset: number): [number, number] {\n let x = 0, y = 0;\n if (radialOffset < 0) radialOffset = 0; // Ignore negative offset.\n // solve for r where r^2 + r^2 = radialOffset^2\n const hypotenuse = radialOffset / Math.SQRT2;\n switch (anchor) {\n case 'top-right':\n case 'top-left':\n y = hypotenuse - baselineOffset;\n break;\n case 'bottom-right':\n case 'bottom-left':\n y = -hypotenuse + baselineOffset;\n break;\n case 'bottom':\n y = -radialOffset + baselineOffset;\n break;\n case 'top':\n y = radialOffset - baselineOffset;\n break;\n }\n\n switch (anchor) {\n case 'top-right':\n case 'bottom-right':\n x = -hypotenuse;\n break;\n case 'top-left':\n case 'bottom-left':\n x = hypotenuse;\n break;\n case 'left':\n x = radialOffset;\n break;\n case 'right':\n x = -radialOffset;\n break;\n }\n\n return [x, y];\n }\n\n function fromTextOffset(anchor: TextAnchor, offsetX: number, offsetY: number): [number, number] {\n let x = 0, y = 0;\n // Use absolute offset values.\n offsetX = Math.abs(offsetX);\n offsetY = Math.abs(offsetY);\n\n switch (anchor) {\n case 'top-right':\n case 'top-left':\n case 'top':\n y = offsetY - baselineOffset;\n break;\n case 'bottom-right':\n case 'bottom-left':\n case 'bottom':\n y = -offsetY + baselineOffset;\n break;\n }\n\n switch (anchor) {\n case 'top-right':\n case 'bottom-right':\n case 'right':\n x = -offsetX;\n break;\n case 'top-left':\n case 'bottom-left':\n case 'left':\n x = offsetX;\n break;\n }\n\n return [x, y];\n }\n\n return (offset[1] !== INVALID_TEXT_OFFSET) ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]);\n}\n\n// Helper to support both text-variable-anchor and text-variable-anchor-offset. Offset values converted from EMs to PXs\nexport function getTextVariableAnchorOffset(layer: SymbolStyleLayer, feature: SymbolFeature, canonical: CanonicalTileID): VariableAnchorOffsetCollection | null {\n const layout = layer.layout;\n // If style specifies text-variable-anchor-offset, just return it\n const variableAnchorOffset = layout.get('text-variable-anchor-offset')?.evaluate(feature, {}, canonical);\n\n if (variableAnchorOffset) {\n const sourceValues = variableAnchorOffset.values;\n const destValues: VariableAnchorOffsetCollectionSpecification = [];\n\n // Convert offsets from EM to PX, and apply baseline shift\n for (let i = 0; i < sourceValues.length; i += 2) {\n const anchor = destValues[i] = sourceValues[i] as TextAnchor;\n const offset = (sourceValues[i + 1] as [number, number]).map(t => t * ONE_EM) as [number, number];\n\n if (anchor.startsWith('top')) {\n offset[1] -= baselineOffset;\n } else if (anchor.startsWith('bottom')) {\n offset[1] += baselineOffset;\n }\n\n destValues[i + 1] = offset;\n }\n\n return new VariableAnchorOffsetCollection(destValues);\n }\n\n // If style specifies text-variable-anchor, convert to the new format\n const variableAnchor = layout.get('text-variable-anchor');\n\n if (variableAnchor) {\n let textOffset: [number, number];\n const unevaluatedLayout = layer._unevaluatedLayout;\n\n // The style spec says don't use `text-offset` and `text-radial-offset` together\n // but doesn't actually specify what happens if you use both. We go with the radial offset.\n if (unevaluatedLayout.getValue('text-radial-offset') !== undefined) {\n textOffset = [layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM, INVALID_TEXT_OFFSET];\n } else {\n textOffset = layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM) as [number, number];\n }\n\n const anchorOffsets: VariableAnchorOffsetCollectionSpecification = [];\n\n for (const anchor of variableAnchor) {\n anchorOffsets.push(anchor, evaluateVariableOffset(anchor, textOffset));\n }\n\n return new VariableAnchorOffsetCollection(anchorOffsets);\n }\n\n return null;\n}\n","import {EXTENT} from '../data/extent';\n\nimport type {OverscaledTileID} from './tile_id';\n\n/**\n * Converts a pixel value at a the given zoom level to tile units.\n *\n * The shaders mostly calculate everything in tile units so style\n * properties need to be converted from pixels to tile units using this.\n *\n * For example, a translation by 30 pixels at zoom 6.5 will be a\n * translation by pixelsToTileUnits(30, 6.5) tile units.\n *\n * @returns value in tile units\n */\nexport function pixelsToTileUnits(\n tile: {\n tileID: OverscaledTileID;\n tileSize: number;\n },\n pixelValue: number,\n z: number\n): number {\n return pixelValue * (EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ)));\n}\n","import {CollisionIndex, viewportPadding} from './collision_index';\nimport type {FeatureKey, PlacedBox, PlacedCircles} from './collision_index';\nimport {EXTENT} from '../data/extent';\nimport * as symbolSize from './symbol_size';\nimport * as projection from './projection';\nimport {getAnchorJustification} from './symbol_layout';\nimport {getAnchorAlignment, WritingMode} from './shaping';\nimport {mat4} from 'gl-matrix';\nimport {pixelsToTileUnits} from '../source/pixels_to_tile_units';\nimport Point from '@mapbox/point-geometry';\nimport type {Transform} from '../geo/transform';\nimport type {StyleLayer} from '../style/style_layer';\nimport {PossiblyEvaluated} from '../style/properties';\nimport type {SymbolLayoutProps, SymbolLayoutPropsPossiblyEvaluated} from '../style/style_layer/symbol_style_layer_properties.g';\nimport {getOverlapMode, OverlapMode} from '../style/style_layer/overlap_mode';\n\nimport type {Tile} from '../source/tile';\nimport {SymbolBucket, CollisionArrays, SingleCollisionBox} from '../data/bucket/symbol_bucket';\n\nimport type {CollisionBoxArray, CollisionVertexArray, SymbolInstance, TextAnchorOffset} from '../data/array_types.g';\nimport type {FeatureIndex} from '../data/feature_index';\nimport type {OverscaledTileID, UnwrappedTileID} from '../source/tile_id';\nimport {Terrain} from '../render/terrain';\nimport {warnOnce} from '../util/util';\nimport {TextAnchor, TextAnchorEnum} from '../style/style_layer/variable_text_anchor';\nimport {Projection} from '../geo/projection/projection';\n\nclass OpacityState {\n opacity: number;\n placed: boolean;\n constructor(prevState: OpacityState, increment: number, placed: boolean, skipFade?: boolean | null) {\n if (prevState) {\n this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment)));\n } else {\n this.opacity = (skipFade && placed) ? 1 : 0;\n }\n this.placed = placed;\n }\n isHidden() {\n return this.opacity === 0 && !this.placed;\n }\n}\n\nclass JointOpacityState {\n text: OpacityState;\n icon: OpacityState;\n constructor(prevState: JointOpacityState, increment: number, placedText: boolean, placedIcon: boolean, skipFade?: boolean | null) {\n this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade);\n this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade);\n }\n isHidden() {\n return this.text.isHidden() && this.icon.isHidden();\n }\n}\n\nclass JointPlacement {\n text: boolean;\n icon: boolean;\n // skipFade = outside viewport, but within CollisionIndex::viewportPadding px of the edge\n // Because these symbols aren't onscreen yet, we can skip the \"fade in\" animation,\n // and if a subsequent viewport change brings them into view, they'll be fully\n // visible right away.\n skipFade: boolean;\n constructor(text: boolean, icon: boolean, skipFade: boolean) {\n this.text = text;\n this.icon = icon;\n this.skipFade = skipFade;\n }\n}\n\nclass CollisionCircleArray {\n // Stores collision circles and placement matrices of a bucket for debug rendering.\n invProjMatrix: mat4;\n viewportMatrix: mat4;\n circles: Array;\n\n constructor() {\n this.invProjMatrix = mat4.create();\n this.viewportMatrix = mat4.create();\n this.circles = [];\n }\n}\n\nexport class RetainedQueryData {\n bucketInstanceId: number;\n featureIndex: FeatureIndex;\n sourceLayerIndex: number;\n bucketIndex: number;\n tileID: OverscaledTileID;\n featureSortOrder: Array;\n constructor(bucketInstanceId: number,\n featureIndex: FeatureIndex,\n sourceLayerIndex: number,\n bucketIndex: number,\n tileID: OverscaledTileID) {\n this.bucketInstanceId = bucketInstanceId;\n this.featureIndex = featureIndex;\n this.sourceLayerIndex = sourceLayerIndex;\n this.bucketIndex = bucketIndex;\n this.tileID = tileID;\n }\n}\n\ntype CollisionGroup = {\n ID: number;\n predicate?: (key: FeatureKey) => boolean;\n};\n\nclass CollisionGroups {\n collisionGroups: {[groupName: string]: CollisionGroup};\n maxGroupID: number;\n crossSourceCollisions: boolean;\n\n constructor(crossSourceCollisions: boolean) {\n this.crossSourceCollisions = crossSourceCollisions;\n this.maxGroupID = 0;\n this.collisionGroups = {};\n }\n\n get(sourceID: string) {\n // The predicate/groupID mechanism allows for arbitrary grouping,\n // but the current interface defines one source == one group when\n // crossSourceCollisions == true.\n if (!this.crossSourceCollisions) {\n if (!this.collisionGroups[sourceID]) {\n const nextGroupID = ++this.maxGroupID;\n this.collisionGroups[sourceID] = {\n ID: nextGroupID,\n predicate: (key) => {\n return key.collisionGroupID === nextGroupID;\n }\n };\n }\n return this.collisionGroups[sourceID];\n } else {\n return {ID: 0, predicate: null};\n }\n }\n}\n\nfunction calculateVariableLayoutShift(\n anchor: TextAnchor,\n width: number,\n height: number,\n textOffset: [number, number],\n textBoxScale: number\n): Point {\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);\n const shiftX = -(horizontalAlign - 0.5) * width;\n const shiftY = -(verticalAlign - 0.5) * height;\n return new Point(\n shiftX + textOffset[0] * textBoxScale,\n shiftY + textOffset[1] * textBoxScale\n );\n}\n\nexport type VariableOffset = {\n textOffset: [number, number];\n width: number;\n height: number;\n anchor: TextAnchor;\n textBoxScale: number;\n prevAnchor?: TextAnchor;\n};\n\ntype TileLayerParameters = {\n bucket: SymbolBucket;\n layout: PossiblyEvaluated;\n translationText: [number, number];\n translationIcon: [number, number];\n unwrappedTileID: UnwrappedTileID;\n posMatrix: mat4;\n textLabelPlaneMatrix: mat4;\n labelToScreenMatrix: mat4;\n scale: number;\n textPixelRatio: number;\n holdingForFade: boolean;\n collisionBoxArray: CollisionBoxArray;\n partiallyEvaluatedTextSize: {\n uSize: number;\n uSizeT: number;\n };\n collisionGroup: CollisionGroup;\n};\n\nexport type BucketPart = {\n sortKey?: number | void;\n symbolInstanceStart: number;\n symbolInstanceEnd: number;\n parameters: TileLayerParameters;\n};\n\nexport type CrossTileID = string | number;\n\nexport class Placement {\n transform: Transform;\n terrain: Terrain;\n collisionIndex: CollisionIndex;\n placements: {\n [_ in CrossTileID]: JointPlacement;\n };\n opacities: {\n [_ in CrossTileID]: JointOpacityState;\n };\n variableOffsets: {\n [_ in CrossTileID]: VariableOffset;\n };\n placedOrientations: {\n [_ in CrossTileID]: number;\n };\n commitTime: number;\n prevZoomAdjustment: number;\n lastPlacementChangeTime: number;\n stale: boolean;\n fadeDuration: number;\n retainedQueryData: {\n [_: number]: RetainedQueryData;\n };\n collisionGroups: CollisionGroups;\n prevPlacement: Placement;\n zoomAtLastRecencyCheck: number;\n collisionCircleArrays: {\n [k in any]: CollisionCircleArray;\n };\n collisionBoxArrays: Map>;\n\n constructor(transform: Transform, projection: Projection, terrain: Terrain, fadeDuration: number, crossSourceCollisions: boolean, prevPlacement?: Placement) {\n this.transform = transform.clone();\n this.terrain = terrain;\n this.collisionIndex = new CollisionIndex(this.transform, projection);\n this.placements = {};\n this.opacities = {};\n this.variableOffsets = {};\n this.stale = false;\n this.commitTime = 0;\n this.fadeDuration = fadeDuration;\n this.retainedQueryData = {};\n this.collisionGroups = new CollisionGroups(crossSourceCollisions);\n this.collisionCircleArrays = {};\n this.collisionBoxArrays = new Map>();\n\n this.prevPlacement = prevPlacement;\n if (prevPlacement) {\n prevPlacement.prevPlacement = undefined; // Only hold on to one placement back\n }\n\n this.placedOrientations = {};\n }\n\n private _getTerrainElevationFunc(tileID: OverscaledTileID) {\n const terrain = this.terrain;\n return terrain ? (x: number, y: number) => terrain.getElevation(tileID, x, y) : null;\n }\n\n getBucketParts(results: Array, styleLayer: StyleLayer, tile: Tile, sortAcrossTiles: boolean) {\n const symbolBucket = (tile.getBucket(styleLayer) as SymbolBucket);\n const bucketFeatureIndex = tile.latestFeatureIndex;\n if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0])\n return;\n\n const collisionBoxArray = tile.collisionBoxArray;\n\n const layout = symbolBucket.layers[0].layout;\n const paint = symbolBucket.layers[0].paint;\n\n const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ);\n const textPixelRatio = tile.tileSize / EXTENT;\n\n const unwrappedTileID = tile.tileID.toUnwrapped();\n\n const posMatrix = this.transform.calculatePosMatrix(unwrappedTileID);\n\n const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\n const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n const pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom);\n\n const translationText = this.collisionIndex.mapProjection.translatePosition(\n this.transform,\n tile,\n paint.get('text-translate'),\n paint.get('text-translate-anchor'),);\n\n const translationIcon = this.collisionIndex.mapProjection.translatePosition(\n this.transform,\n tile,\n paint.get('icon-translate'),\n paint.get('icon-translate-anchor'),);\n\n const textLabelPlaneMatrix = projection.getLabelPlaneMatrix(posMatrix,\n pitchWithMap,\n rotateWithMap,\n this.transform,\n pixelsToTiles);\n\n let labelToScreenMatrix = null;\n\n if (pitchWithMap) {\n const glMatrix = projection.getGlCoordMatrix(\n posMatrix,\n pitchWithMap,\n rotateWithMap,\n this.transform,\n pixelsToTiles);\n\n labelToScreenMatrix = mat4.multiply([] as any, this.transform.labelPlaneMatrix, glMatrix);\n }\n\n // As long as this placement lives, we have to hold onto this bucket's\n // matching FeatureIndex/data for querying purposes\n this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(\n symbolBucket.bucketInstanceId,\n bucketFeatureIndex,\n symbolBucket.sourceLayerIndex,\n symbolBucket.index,\n tile.tileID\n );\n\n const parameters: TileLayerParameters = {\n bucket: symbolBucket,\n layout,\n translationText,\n translationIcon,\n posMatrix,\n unwrappedTileID,\n textLabelPlaneMatrix,\n labelToScreenMatrix,\n scale,\n textPixelRatio,\n holdingForFade: tile.holdingForFade(),\n collisionBoxArray,\n partiallyEvaluatedTextSize: symbolSize.evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom),\n collisionGroup: this.collisionGroups.get(symbolBucket.sourceID)\n };\n\n if (sortAcrossTiles) {\n for (const range of symbolBucket.sortKeyRanges) {\n const {sortKey, symbolInstanceStart, symbolInstanceEnd} = range;\n results.push({sortKey, symbolInstanceStart, symbolInstanceEnd, parameters});\n }\n } else {\n results.push({\n symbolInstanceStart: 0,\n symbolInstanceEnd: symbolBucket.symbolInstances.length,\n parameters\n });\n }\n }\n\n attemptAnchorPlacement(\n textAnchorOffset: TextAnchorOffset,\n textBox: SingleCollisionBox,\n width: number,\n height: number,\n textBoxScale: number,\n rotateWithMap: boolean,\n pitchWithMap: boolean,\n textPixelRatio: number,\n posMatrix: mat4,\n unwrappedTileID,\n collisionGroup: CollisionGroup,\n textOverlapMode: OverlapMode,\n symbolInstance: SymbolInstance,\n bucket: SymbolBucket,\n orientation: number,\n translationText: [number, number],\n translationIcon: [number, number],\n iconBox?: SingleCollisionBox | null,\n getElevation?: (x: number, y: number) => number\n ): {\n shift: Point;\n placedGlyphBoxes: PlacedBox;\n } {\n\n const anchor = TextAnchorEnum[textAnchorOffset.textAnchor] as TextAnchor;\n const textOffset = [textAnchorOffset.textOffset0, textAnchorOffset.textOffset1] as [number, number];\n const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale);\n\n const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(\n textBox,\n textOverlapMode,\n textPixelRatio,\n posMatrix,\n unwrappedTileID,\n pitchWithMap,\n rotateWithMap,\n translationText,\n collisionGroup.predicate,\n getElevation,\n shift\n );\n\n if (iconBox) {\n const placedIconBoxes = this.collisionIndex.placeCollisionBox(\n iconBox,\n textOverlapMode,\n textPixelRatio,\n posMatrix,\n unwrappedTileID,\n pitchWithMap,\n rotateWithMap,\n translationIcon,\n collisionGroup.predicate,\n getElevation,\n shift\n );\n if (!placedIconBoxes.placeable) return;\n }\n\n if (placedGlyphBoxes.placeable) {\n let prevAnchor;\n // If this label was placed in the previous placement, record the anchor position\n // to allow us to animate the transition\n if (this.prevPlacement &&\n this.prevPlacement.variableOffsets[symbolInstance.crossTileID] &&\n this.prevPlacement.placements[symbolInstance.crossTileID] &&\n this.prevPlacement.placements[symbolInstance.crossTileID].text) {\n prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor;\n }\n if (symbolInstance.crossTileID === 0) throw new Error('symbolInstance.crossTileID can\\'t be 0');\n this.variableOffsets[symbolInstance.crossTileID] = {\n textOffset,\n width,\n height,\n anchor,\n textBoxScale,\n prevAnchor\n };\n this.markUsedJustification(bucket, anchor, symbolInstance, orientation);\n\n if (bucket.allowVerticalPlacement) {\n this.markUsedOrientation(bucket, orientation, symbolInstance);\n this.placedOrientations[symbolInstance.crossTileID] = orientation;\n }\n\n return {shift, placedGlyphBoxes};\n }\n }\n\n placeLayerBucketPart(bucketPart: BucketPart, seenCrossTileIDs: {\n [k in string | number]: boolean;\n }, showCollisionBoxes: boolean) {\n\n const {\n bucket,\n layout,\n translationText,\n translationIcon,\n posMatrix,\n unwrappedTileID,\n textLabelPlaneMatrix,\n labelToScreenMatrix,\n textPixelRatio,\n holdingForFade,\n collisionBoxArray,\n partiallyEvaluatedTextSize,\n collisionGroup\n } = bucketPart.parameters;\n\n const textOptional = layout.get('text-optional');\n const iconOptional = layout.get('icon-optional');\n const textOverlapMode = getOverlapMode(layout, 'text-overlap', 'text-allow-overlap');\n const textAlwaysOverlap = textOverlapMode === 'always';\n const iconOverlapMode = getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap');\n const iconAlwaysOverlap = iconOverlapMode === 'always';\n const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\n const hasIconTextFit = layout.get('icon-text-fit') !== 'none';\n const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y';\n\n // This logic is similar to the \"defaultOpacityState\" logic below in updateBucketOpacities\n // If we know a symbol is always supposed to show, force it to be marked visible even if\n // it wasn't placed into the collision index (because some or all of it was outside the range\n // of the collision grid).\n // There is a subtle edge case here we're accepting:\n // Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false\n // A's icon is outside the grid, so doesn't get placed\n // A's text would be inside grid, but doesn't get placed because of icon-optional: false\n // We still show A because of the allow-overlap settings.\n // Symbol B has allow-overlap: false, and gets placed where A's text would be\n // On panning in, there is a short period when Symbol B and Symbol A will overlap\n // This is the reverse of our normal policy of \"fade in on pan\", but should look like any other\n // collision and hopefully not be too noticeable.\n // See https://github.com/mapbox/mapbox-gl-js/issues/7172\n const alwaysShowText = textAlwaysOverlap && (iconAlwaysOverlap || !bucket.hasIconData() || iconOptional);\n const alwaysShowIcon = iconAlwaysOverlap && (textAlwaysOverlap || !bucket.hasTextData() || textOptional);\n\n if (!bucket.collisionArrays && collisionBoxArray) {\n bucket.deserializeCollisionBoxes(collisionBoxArray);\n }\n\n const tileID = this.retainedQueryData[bucket.bucketInstanceId].tileID;\n const getElevation = this._getTerrainElevationFunc(tileID);\n\n const placeSymbol = (symbolInstance: SymbolInstance, collisionArrays: CollisionArrays, symbolIndex: number) => {\n if (seenCrossTileIDs[symbolInstance.crossTileID]) return;\n if (holdingForFade) {\n // Mark all symbols from this tile as \"not placed\", but don't add to seenCrossTileIDs, because we don't\n // know yet if we have a duplicate in a parent tile that _should_ be placed.\n this.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false);\n return;\n }\n\n let placeText = false;\n let placeIcon = false;\n let offscreen = true;\n let shift = null;\n\n let placed: PlacedBox = {box: null, placeable: false, offscreen: null};\n let placedVerticalText = {box: null, placeable: false, offscreen: null};\n\n let placedGlyphBoxes: PlacedBox = null;\n let placedGlyphCircles: PlacedCircles = null;\n let placedIconBoxes: PlacedBox = null;\n let textFeatureIndex = 0;\n let verticalTextFeatureIndex = 0;\n let iconFeatureIndex = 0;\n\n if (collisionArrays.textFeatureIndex) {\n textFeatureIndex = collisionArrays.textFeatureIndex;\n } else if (symbolInstance.useRuntimeCollisionCircles) {\n textFeatureIndex = symbolInstance.featureIndex;\n }\n if (collisionArrays.verticalTextFeatureIndex) {\n verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex;\n }\n\n const textBox = collisionArrays.textBox;\n if (textBox) {\n\n const updatePreviousOrientationIfNotPlaced = (isPlaced) => {\n let previousOrientation = WritingMode.horizontal;\n if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) {\n const prevPlacedOrientation = this.prevPlacement.placedOrientations[symbolInstance.crossTileID];\n if (prevPlacedOrientation) {\n this.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation;\n previousOrientation = prevPlacedOrientation;\n this.markUsedOrientation(bucket, previousOrientation, symbolInstance);\n }\n }\n return previousOrientation;\n };\n\n const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => {\n if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) {\n for (const placementMode of bucket.writingModes) {\n if (placementMode === WritingMode.vertical) {\n placed = placeVerticalFn();\n placedVerticalText = placed;\n } else {\n placed = placeHorizontalFn();\n }\n if (placed && placed.placeable) break;\n }\n } else {\n placed = placeHorizontalFn();\n }\n };\n\n const textAnchorOffsetStart = symbolInstance.textAnchorOffsetStartIndex;\n const textAnchorOffsetEnd = symbolInstance.textAnchorOffsetEndIndex;\n\n // If start+end indices match, text-variable-anchor is not in play.\n if (textAnchorOffsetEnd === textAnchorOffsetStart) {\n const placeBox = (collisionTextBox, orientation) => {\n const placedFeature = this.collisionIndex.placeCollisionBox(\n collisionTextBox,\n textOverlapMode,\n textPixelRatio,\n posMatrix,\n unwrappedTileID,\n pitchWithMap,\n rotateWithMap,\n translationText,\n collisionGroup.predicate,\n getElevation\n );\n if (placedFeature && placedFeature.placeable) {\n this.markUsedOrientation(bucket, orientation, symbolInstance);\n this.placedOrientations[symbolInstance.crossTileID] = orientation;\n }\n return placedFeature;\n };\n\n const placeHorizontal = () => {\n return placeBox(textBox, WritingMode.horizontal);\n };\n\n const placeVertical = () => {\n const verticalTextBox = collisionArrays.verticalTextBox;\n if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {\n return placeBox(verticalTextBox, WritingMode.vertical);\n }\n return {box: null, offscreen: null};\n };\n\n placeTextForPlacementModes(placeHorizontal, placeVertical);\n updatePreviousOrientationIfNotPlaced(placed && placed.placeable);\n\n } else {\n // If this symbol was in the last placement, prefer placement using same anchor, if it's still available\n let prevAnchor = TextAnchorEnum[this.prevPlacement?.variableOffsets[symbolInstance.crossTileID]?.anchor];\n\n const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => {\n const width = collisionTextBox.x2 - collisionTextBox.x1;\n const height = collisionTextBox.y2 - collisionTextBox.y1;\n const textBoxScale = symbolInstance.textBoxScale;\n const variableIconBox = hasIconTextFit && (iconOverlapMode === 'never') ? collisionIconBox : null;\n\n let placedBox: PlacedBox = null;\n let placementPasses = (textOverlapMode === 'never') ? 1 : 2;\n let overlapMode: OverlapMode = 'never';\n\n if (prevAnchor) {\n placementPasses++;\n }\n\n for (let pass = 0; pass < placementPasses; pass++) {\n for (let i = textAnchorOffsetStart; i < textAnchorOffsetEnd; i++) {\n const textAnchorOffset = bucket.textAnchorOffsets.get(i);\n\n if (prevAnchor && textAnchorOffset.textAnchor !== prevAnchor) {\n continue;\n }\n\n const result = this.attemptAnchorPlacement(\n textAnchorOffset, collisionTextBox, width, height,\n textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, unwrappedTileID,\n collisionGroup, overlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, variableIconBox, getElevation);\n\n if (result) {\n placedBox = result.placedGlyphBoxes;\n if (placedBox && placedBox.placeable) {\n placeText = true;\n shift = result.shift;\n return placedBox;\n }\n }\n }\n\n if (prevAnchor) {\n prevAnchor = null;\n } else {\n overlapMode = textOverlapMode;\n }\n }\n\n if (showCollisionBoxes && !placedBox) {\n // No box was successfully placed\n // Generate bounds for a fake centered box, so that we can at least display something for collision debug.\n const placedFakeGlyphBox = this.collisionIndex.placeCollisionBox(\n textBox,\n 'always', // Skips expensive collision check with already placed boxes\n textPixelRatio,\n posMatrix,\n unwrappedTileID,\n pitchWithMap,\n rotateWithMap,\n translationText,\n collisionGroup.predicate,\n getElevation,\n new Point(0, 0)\n );\n placedBox = {\n box: placedFakeGlyphBox.box,\n offscreen: false,\n placeable: false\n };\n }\n\n return placedBox;\n };\n\n const placeHorizontal = () => {\n return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, WritingMode.horizontal);\n };\n\n const placeVertical = () => {\n const verticalTextBox = collisionArrays.verticalTextBox;\n const wasPlaced = placed && placed.placeable;\n if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {\n return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, WritingMode.vertical);\n }\n return {box: null, occluded: true, offscreen: null};\n };\n\n placeTextForPlacementModes(placeHorizontal, placeVertical);\n\n if (placed) {\n placeText = placed.placeable;\n offscreen = placed.offscreen;\n }\n\n const prevOrientation = updatePreviousOrientationIfNotPlaced(placed && placed.placeable);\n\n // If we didn't get placed, we still need to copy our position from the last placement for\n // fade animations\n if (!placeText && this.prevPlacement) {\n const prevOffset = this.prevPlacement.variableOffsets[symbolInstance.crossTileID];\n if (prevOffset) {\n this.variableOffsets[symbolInstance.crossTileID] = prevOffset;\n this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation);\n }\n }\n\n }\n }\n\n placedGlyphBoxes = placed;\n placeText = placedGlyphBoxes && placedGlyphBoxes.placeable;\n\n offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen;\n\n if (symbolInstance.useRuntimeCollisionCircles) {\n const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex);\n const fontSize = symbolSize.evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol);\n\n const textPixelPadding = layout.get('text-padding');\n const circlePixelDiameter = symbolInstance.collisionCircleDiameter;\n\n placedGlyphCircles = this.collisionIndex.placeCollisionCircles(\n textOverlapMode,\n placedSymbol,\n bucket.lineVertexArray,\n bucket.glyphOffsetArray,\n fontSize,\n posMatrix,\n unwrappedTileID,\n textLabelPlaneMatrix,\n labelToScreenMatrix,\n showCollisionBoxes,\n pitchWithMap,\n collisionGroup.predicate,\n circlePixelDiameter,\n textPixelPadding,\n translationText,\n getElevation\n );\n\n if (placedGlyphCircles.circles.length && placedGlyphCircles.collisionDetected && !showCollisionBoxes) {\n warnOnce('Collisions detected, but collision boxes are not shown');\n }\n\n // If text-overlap is set to 'always', force \"placedCircles\" to true\n // In theory there should always be at least one circle placed\n // in this case, but for now quirks in text-anchor\n // and text-offset may prevent that from being true.\n placeText = textAlwaysOverlap || (placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected);\n offscreen = offscreen && placedGlyphCircles.offscreen;\n }\n\n if (collisionArrays.iconFeatureIndex) {\n iconFeatureIndex = collisionArrays.iconFeatureIndex;\n }\n\n if (collisionArrays.iconBox) {\n const placeIconFeature = iconBox => {\n return this.collisionIndex.placeCollisionBox(\n iconBox,\n iconOverlapMode,\n textPixelRatio,\n posMatrix,\n unwrappedTileID,\n pitchWithMap,\n rotateWithMap,\n translationIcon,\n collisionGroup.predicate,\n getElevation,\n (hasIconTextFit && shift) ? shift : undefined,\n );\n };\n\n if (placedVerticalText && placedVerticalText.placeable && collisionArrays.verticalIconBox) {\n placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox);\n placeIcon = placedIconBoxes.placeable;\n } else {\n placedIconBoxes = placeIconFeature(collisionArrays.iconBox);\n placeIcon = placedIconBoxes.placeable;\n }\n offscreen = offscreen && placedIconBoxes.offscreen;\n }\n\n const iconWithoutText = textOptional ||\n (symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0);\n const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0;\n\n // Combine the scales for icons and text.\n if (!iconWithoutText && !textWithoutIcon) {\n placeIcon = placeText = placeIcon && placeText;\n } else if (!textWithoutIcon) {\n placeText = placeIcon && placeText;\n } else if (!iconWithoutText) {\n placeIcon = placeIcon && placeText;\n }\n\n const hasTextBox = placeText && placedGlyphBoxes.placeable;\n const hasIconBox = placeIcon && placedIconBoxes.placeable;\n\n if (hasTextBox) {\n if (placedVerticalText && placedVerticalText.placeable && verticalTextFeatureIndex) {\n this.collisionIndex.insertCollisionBox(\n placedGlyphBoxes.box,\n textOverlapMode,\n layout.get('text-ignore-placement'),\n bucket.bucketInstanceId,\n verticalTextFeatureIndex,\n collisionGroup.ID);\n } else {\n this.collisionIndex.insertCollisionBox(\n placedGlyphBoxes.box,\n textOverlapMode,\n layout.get('text-ignore-placement'),\n bucket.bucketInstanceId,\n textFeatureIndex,\n collisionGroup.ID);\n }\n\n }\n if (hasIconBox) {\n this.collisionIndex.insertCollisionBox(\n placedIconBoxes.box,\n iconOverlapMode,\n layout.get('icon-ignore-placement'),\n bucket.bucketInstanceId,\n iconFeatureIndex,\n collisionGroup.ID);\n }\n if (placedGlyphCircles) {\n if (placeText) {\n this.collisionIndex.insertCollisionCircles(\n placedGlyphCircles.circles,\n textOverlapMode,\n layout.get('text-ignore-placement'),\n bucket.bucketInstanceId,\n textFeatureIndex,\n collisionGroup.ID);\n }\n }\n\n if (showCollisionBoxes) {\n this.storeCollisionData(bucket.bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles);\n }\n\n if (symbolInstance.crossTileID === 0) throw new Error('symbolInstance.crossTileID can\\'t be 0');\n if (bucket.bucketInstanceId === 0) throw new Error('bucket.bucketInstanceId can\\'t be 0');\n\n this.placements[symbolInstance.crossTileID] = new JointPlacement(placeText || alwaysShowText, placeIcon || alwaysShowIcon, offscreen || bucket.justReloaded);\n seenCrossTileIDs[symbolInstance.crossTileID] = true;\n };\n\n if (zOrderByViewportY) {\n if (bucketPart.symbolInstanceStart !== 0) throw new Error('bucket.bucketInstanceId should be 0');\n const symbolIndexes = bucket.getSortedSymbolIndexes(this.transform.angle);\n for (let i = symbolIndexes.length - 1; i >= 0; --i) {\n const symbolIndex = symbolIndexes[i];\n placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex], symbolIndex);\n }\n } else {\n for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) {\n placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i], i);\n }\n }\n\n if (showCollisionBoxes && bucket.bucketInstanceId in this.collisionCircleArrays) {\n const circleArray = this.collisionCircleArrays[bucket.bucketInstanceId];\n\n // Store viewport and inverse projection matrices per bucket\n mat4.invert(circleArray.invProjMatrix, posMatrix);\n circleArray.viewportMatrix = this.collisionIndex.getViewportMatrix();\n }\n\n bucket.justReloaded = false;\n }\n\n storeCollisionData(bucketInstanceId: number, symbolIndex: number, collisionArrays: CollisionArrays, placedGlyphBoxes: PlacedBox, placedIconBoxes: PlacedBox, placedGlyphCircles: PlacedCircles): void {\n if (collisionArrays.textBox || collisionArrays.iconBox) {\n // Store the actually used collision box for debug draw\n let boxArray: Map;\n\n if (this.collisionBoxArrays.has(bucketInstanceId)) {\n boxArray = this.collisionBoxArrays.get(bucketInstanceId);\n } else {\n boxArray = new Map();\n this.collisionBoxArrays.set(bucketInstanceId, boxArray);\n }\n let realCollisionBox: {\n text: number[];\n icon: number[];\n };\n\n if (boxArray.has(symbolIndex)) {\n realCollisionBox = boxArray.get(symbolIndex);\n } else {\n realCollisionBox = {\n text: null,\n icon: null\n };\n boxArray.set(symbolIndex, realCollisionBox);\n }\n\n if (collisionArrays.textBox) {\n realCollisionBox.text = placedGlyphBoxes.box;\n }\n if (collisionArrays.iconBox) {\n realCollisionBox.icon = placedIconBoxes.box;\n }\n }\n\n if (placedGlyphCircles) {\n let circleArray = this.collisionCircleArrays[bucketInstanceId];\n\n // Group collision circles together by bucket. Circles can't be pushed forward for rendering yet as the symbol placement\n // for a bucket is not guaranteed to be complete before the commit-function has been called\n if (circleArray === undefined)\n circleArray = this.collisionCircleArrays[bucketInstanceId] = new CollisionCircleArray();\n\n for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) {\n circleArray.circles.push(placedGlyphCircles.circles[i + 0]); // x\n circleArray.circles.push(placedGlyphCircles.circles[i + 1]); // y\n circleArray.circles.push(placedGlyphCircles.circles[i + 2]); // radius\n circleArray.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0); // collisionDetected-flag\n }\n }\n }\n\n markUsedJustification(bucket: SymbolBucket, placedAnchor: TextAnchor, symbolInstance: SymbolInstance, orientation: number) {\n const justifications = {\n 'left': symbolInstance.leftJustifiedTextSymbolIndex,\n 'center': symbolInstance.centerJustifiedTextSymbolIndex,\n 'right': symbolInstance.rightJustifiedTextSymbolIndex\n };\n\n let autoIndex;\n if (orientation === WritingMode.vertical) {\n autoIndex = symbolInstance.verticalPlacedTextSymbolIndex;\n } else {\n autoIndex = justifications[getAnchorJustification(placedAnchor)];\n }\n\n const indexes = [\n symbolInstance.leftJustifiedTextSymbolIndex,\n symbolInstance.centerJustifiedTextSymbolIndex,\n symbolInstance.rightJustifiedTextSymbolIndex,\n symbolInstance.verticalPlacedTextSymbolIndex\n ];\n\n for (const index of indexes) {\n if (index >= 0) {\n if (autoIndex >= 0 && index !== autoIndex) {\n // There are multiple justifications and this one isn't it: shift offscreen\n bucket.text.placedSymbolArray.get(index).crossTileID = 0;\n } else {\n // Either this is the chosen justification or the justification is hardwired: use this one\n bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID;\n }\n }\n }\n }\n\n markUsedOrientation(bucket: SymbolBucket, orientation: number, symbolInstance: SymbolInstance) {\n const horizontal = (orientation === WritingMode.horizontal || orientation === WritingMode.horizontalOnly) ? orientation : 0;\n const vertical = orientation === WritingMode.vertical ? orientation : 0;\n\n const horizontalIndexes = [\n symbolInstance.leftJustifiedTextSymbolIndex,\n symbolInstance.centerJustifiedTextSymbolIndex,\n symbolInstance.rightJustifiedTextSymbolIndex\n ];\n\n for (const index of horizontalIndexes) {\n bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal;\n }\n\n if (symbolInstance.verticalPlacedTextSymbolIndex) {\n bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical;\n }\n }\n\n commit(now: number): void {\n this.commitTime = now;\n this.zoomAtLastRecencyCheck = this.transform.zoom;\n\n const prevPlacement = this.prevPlacement;\n let placementChanged = false;\n\n this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0;\n const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1;\n\n const prevOpacities = prevPlacement ? prevPlacement.opacities : {};\n const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {};\n const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {};\n\n // add the opacities from the current placement, and copy their current values from the previous placement\n for (const crossTileID in this.placements) {\n const jointPlacement = this.placements[crossTileID];\n const prevOpacity = prevOpacities[crossTileID];\n if (prevOpacity) {\n this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon);\n placementChanged = placementChanged ||\n jointPlacement.text !== prevOpacity.text.placed ||\n jointPlacement.icon !== prevOpacity.icon.placed;\n } else {\n this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade);\n placementChanged = placementChanged || jointPlacement.text || jointPlacement.icon;\n }\n }\n\n // copy and update values from the previous placement that aren't in the current placement but haven't finished fading\n for (const crossTileID in prevOpacities) {\n const prevOpacity = prevOpacities[crossTileID];\n if (!this.opacities[crossTileID]) {\n const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false);\n if (!jointOpacity.isHidden()) {\n this.opacities[crossTileID] = jointOpacity;\n placementChanged = placementChanged || prevOpacity.text.placed || prevOpacity.icon.placed;\n }\n }\n }\n for (const crossTileID in prevOffsets) {\n if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) {\n this.variableOffsets[crossTileID] = prevOffsets[crossTileID];\n }\n }\n\n for (const crossTileID in prevOrientations) {\n if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) {\n this.placedOrientations[crossTileID] = prevOrientations[crossTileID];\n }\n }\n\n // this.lastPlacementChangeTime is the time of the last commit() that\n // resulted in a placement change -- in other words, the start time of\n // the last symbol fade animation\n if (prevPlacement && prevPlacement.lastPlacementChangeTime === undefined) {\n throw new Error('Last placement time for previous placement is not defined');\n }\n if (placementChanged) {\n this.lastPlacementChangeTime = now;\n } else if (typeof this.lastPlacementChangeTime !== 'number') {\n this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now;\n }\n }\n\n updateLayerOpacities(styleLayer: StyleLayer, tiles: Array) {\n const seenCrossTileIDs = {};\n for (const tile of tiles) {\n const symbolBucket = tile.getBucket(styleLayer) as SymbolBucket;\n if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) {\n this.updateBucketOpacities(symbolBucket, tile.tileID, seenCrossTileIDs, tile.collisionBoxArray);\n }\n }\n }\n\n updateBucketOpacities(bucket: SymbolBucket, tileID: OverscaledTileID, seenCrossTileIDs: {\n [k in string | number]: boolean;\n }, collisionBoxArray?: CollisionBoxArray | null) {\n if (bucket.hasTextData()) {\n bucket.text.opacityVertexArray.clear();\n bucket.text.hasVisibleVertices = false;\n }\n if (bucket.hasIconData()) {\n bucket.icon.opacityVertexArray.clear();\n bucket.icon.hasVisibleVertices = false;\n }\n if (bucket.hasIconCollisionBoxData()) bucket.iconCollisionBox.collisionVertexArray.clear();\n if (bucket.hasTextCollisionBoxData()) bucket.textCollisionBox.collisionVertexArray.clear();\n\n const layer = bucket.layers[0];\n const layout = layer.layout;\n const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true);\n const textAllowOverlap = layout.get('text-allow-overlap');\n const iconAllowOverlap = layout.get('icon-allow-overlap');\n const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset');\n const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\n const hasIconTextFit = layout.get('icon-text-fit') !== 'none';\n // If allow-overlap is true, we can show symbols before placement runs on them\n // But we have to wait for placement if we potentially depend on a paired icon/text\n // with allow-overlap: false.\n // See https://github.com/mapbox/mapbox-gl-js/issues/7032\n const defaultOpacityState = new JointOpacityState(null, 0,\n textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get('icon-optional')),\n iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get('text-optional')),\n true);\n\n if (!bucket.collisionArrays && collisionBoxArray && ((bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()))) {\n bucket.deserializeCollisionBoxes(collisionBoxArray);\n }\n\n const addOpacities = (iconOrText, numVertices: number, opacity: number) => {\n for (let i = 0; i < numVertices / 4; i++) {\n iconOrText.opacityVertexArray.emplaceBack(opacity);\n }\n iconOrText.hasVisibleVertices = iconOrText.hasVisibleVertices || (opacity !== PACKED_HIDDEN_OPACITY);\n };\n\n const boxArrays = this.collisionBoxArrays.get(bucket.bucketInstanceId);\n\n for (let s = 0; s < bucket.symbolInstances.length; s++) {\n const symbolInstance = bucket.symbolInstances.get(s);\n const {\n numHorizontalGlyphVertices,\n numVerticalGlyphVertices,\n crossTileID\n } = symbolInstance;\n\n const isDuplicate = seenCrossTileIDs[crossTileID];\n\n let opacityState = this.opacities[crossTileID];\n if (isDuplicate) {\n opacityState = duplicateOpacityState;\n } else if (!opacityState) {\n opacityState = defaultOpacityState;\n // store the state so that future placements use it as a starting point\n this.opacities[crossTileID] = opacityState;\n }\n\n seenCrossTileIDs[crossTileID] = true;\n\n const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0;\n const hasIcon = symbolInstance.numIconVertices > 0;\n\n const placedOrientation = this.placedOrientations[symbolInstance.crossTileID];\n const horizontalHidden = placedOrientation === WritingMode.vertical;\n const verticalHidden = placedOrientation === WritingMode.horizontal || placedOrientation === WritingMode.horizontalOnly;\n\n if (hasText) {\n const packedOpacity = packOpacity(opacityState.text);\n // Vertical text fades in/out on collision the same way as corresponding\n // horizontal text. Switch between vertical/horizontal should be instantaneous\n const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;\n addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity);\n const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;\n addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity);\n\n // If this label is completely faded, mark it so that we don't have to calculate\n // its position at render time. If this layer has variable placement, shift the various\n // symbol instances appropriately so that symbols from buckets that have yet to be placed\n // offset appropriately.\n const symbolHidden = opacityState.text.isHidden();\n [\n symbolInstance.rightJustifiedTextSymbolIndex,\n symbolInstance.centerJustifiedTextSymbolIndex,\n symbolInstance.leftJustifiedTextSymbolIndex\n ].forEach(index => {\n if (index >= 0) {\n bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0;\n }\n });\n\n if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {\n bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0;\n }\n\n const prevOffset = this.variableOffsets[symbolInstance.crossTileID];\n if (prevOffset) {\n this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation);\n }\n\n const prevOrientation = this.placedOrientations[symbolInstance.crossTileID];\n if (prevOrientation) {\n this.markUsedJustification(bucket, 'left', symbolInstance, prevOrientation);\n this.markUsedOrientation(bucket, prevOrientation, symbolInstance);\n }\n }\n\n if (hasIcon) {\n const packedOpacity = packOpacity(opacityState.icon);\n\n const useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden);\n\n if (symbolInstance.placedIconSymbolIndex >= 0) {\n const horizontalOpacity = useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY;\n addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity);\n bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden =\n (opacityState.icon.isHidden() as any);\n }\n\n if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) {\n const verticalOpacity = !useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY;\n addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity);\n bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden =\n (opacityState.icon.isHidden() as any);\n }\n }\n\n const realBoxes = (boxArrays && boxArrays.has(s)) ? boxArrays.get(s) : {\n text: null,\n icon: null\n };\n\n if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) {\n const collisionArrays = bucket.collisionArrays[s];\n if (collisionArrays) {\n let shift = new Point(0, 0);\n if (collisionArrays.textBox || collisionArrays.verticalTextBox) {\n let used = true;\n if (hasVariablePlacement) {\n const variableOffset = this.variableOffsets[crossTileID];\n if (variableOffset) {\n // This will show either the currently placed position or the last\n // successfully placed position (so you can visualize what collision\n // just made the symbol disappear, and the most likely place for the\n // symbol to come back)\n shift = calculateVariableLayoutShift(variableOffset.anchor,\n variableOffset.width,\n variableOffset.height,\n variableOffset.textOffset,\n variableOffset.textBoxScale);\n if (rotateWithMap) {\n shift._rotate(pitchWithMap ? this.transform.angle : -this.transform.angle);\n }\n } else {\n // No offset -> this symbol hasn't been placed since coming on-screen\n // No single box is particularly meaningful and all of them would be too noisy\n // Use the center box just to show something's there, but mark it \"not used\"\n used = false;\n }\n }\n\n if (collisionArrays.textBox || collisionArrays.verticalTextBox) {\n let hidden: boolean;\n if (collisionArrays.textBox) {\n hidden = horizontalHidden;\n }\n if (collisionArrays.verticalTextBox) {\n hidden = verticalHidden;\n }\n updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || hidden, realBoxes.text, shift.x, shift.y);\n }\n }\n\n if (collisionArrays.iconBox || collisionArrays.verticalIconBox) {\n const verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox);\n let hidden: boolean;\n if (collisionArrays.iconBox) {\n hidden = verticalIconUsed;\n }\n if (collisionArrays.verticalIconBox) {\n hidden = !verticalIconUsed;\n }\n updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, hidden, realBoxes.icon,\n hasIconTextFit ? shift.x : 0,\n hasIconTextFit ? shift.y : 0);\n }\n }\n }\n }\n\n bucket.sortFeatures(this.transform.angle);\n if (this.retainedQueryData[bucket.bucketInstanceId]) {\n this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder;\n }\n\n if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) {\n bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray);\n }\n if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) {\n bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray);\n }\n if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) {\n bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray);\n }\n if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) {\n bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray);\n }\n\n if (bucket.text.opacityVertexArray.length !== bucket.text.layoutVertexArray.length / 4) throw new Error(`bucket.text.opacityVertexArray.length (= ${bucket.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${bucket.text.layoutVertexArray.length}) / 4`);\n if (bucket.icon.opacityVertexArray.length !== bucket.icon.layoutVertexArray.length / 4) throw new Error(`bucket.icon.opacityVertexArray.length (= ${bucket.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${bucket.icon.layoutVertexArray.length}) / 4`);\n\n // Push generated collision circles to the bucket for debug rendering\n if (bucket.bucketInstanceId in this.collisionCircleArrays) {\n const instance = this.collisionCircleArrays[bucket.bucketInstanceId];\n\n bucket.placementInvProjMatrix = instance.invProjMatrix;\n bucket.placementViewportMatrix = instance.viewportMatrix;\n bucket.collisionCircleArray = instance.circles;\n\n delete this.collisionCircleArrays[bucket.bucketInstanceId];\n }\n }\n\n symbolFadeChange(now: number) {\n return this.fadeDuration === 0 ?\n 1 :\n ((now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment);\n }\n\n zoomAdjustment(zoom: number) {\n // When zooming out quickly, labels can overlap each other. This\n // adjustment is used to reduce the interval between placement calculations\n // and to reduce the fade duration when zooming out quickly. Discovering the\n // collisions more quickly and fading them more quickly reduces the unwanted effect.\n return Math.max(0, (this.transform.zoom - zoom) / 1.5);\n }\n\n hasTransitions(now: number) {\n return this.stale ||\n now - this.lastPlacementChangeTime < this.fadeDuration;\n }\n\n stillRecent(now: number, zoom: number) {\n // The adjustment makes placement more frequent when zooming.\n // This condition applies the adjustment only after the map has\n // stopped zooming. This avoids adding extra jank while zooming.\n const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ?\n (1 - this.zoomAdjustment(zoom)) :\n 1;\n this.zoomAtLastRecencyCheck = zoom;\n\n return this.commitTime + this.fadeDuration * durationAdjustment > now;\n }\n\n setStale() {\n this.stale = true;\n }\n}\n\nfunction updateCollisionVertices(collisionVertexArray: CollisionVertexArray, placed: boolean, notUsed: boolean | number, realBox: Array, shiftX?: number, shiftY?: number) {\n if (!realBox || realBox.length === 0) {\n realBox = [0, 0, 0, 0];\n }\n\n const tlX = realBox[0] - viewportPadding;\n const tlY = realBox[1] - viewportPadding;\n const brX = realBox[2] - viewportPadding;\n const brY = realBox[3] - viewportPadding;\n\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, tlY);\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, tlY);\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, brY);\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, brY);\n}\n\n// All four vertices for a glyph will have the same opacity state\n// So we pack the opacity into a uint8, and then repeat it four times\n// to make a single uint32 that we can upload for each glyph in the\n// label.\nconst shift25 = Math.pow(2, 25);\nconst shift24 = Math.pow(2, 24);\nconst shift17 = Math.pow(2, 17);\nconst shift16 = Math.pow(2, 16);\nconst shift9 = Math.pow(2, 9);\nconst shift8 = Math.pow(2, 8);\nconst shift1 = Math.pow(2, 1);\nfunction packOpacity(opacityState: OpacityState): number {\n if (opacityState.opacity === 0 && !opacityState.placed) {\n return 0;\n } else if (opacityState.opacity === 1 && opacityState.placed) {\n return 4294967295;\n }\n const targetBit = opacityState.placed ? 1 : 0;\n const opacityBits = Math.floor(opacityState.opacity * 127);\n return opacityBits * shift25 + targetBit * shift24 +\n opacityBits * shift17 + targetBit * shift16 +\n opacityBits * shift9 + targetBit * shift8 +\n opacityBits * shift1 + targetBit;\n}\n\nconst PACKED_HIDDEN_OPACITY = 0;\n","import {Anchor} from './anchor';\n\nimport {getAnchors, getCenterAnchor} from './get_anchors';\nimport {clipLine} from './clip_line';\nimport {shapeText, shapeIcon, WritingMode, fitIconToText} from './shaping';\nimport {getGlyphQuads, getIconQuads} from './quads';\nimport {CollisionFeature} from './collision_feature';\nimport {warnOnce} from '../util/util';\nimport {\n allowsVerticalWritingMode,\n allowsLetterSpacing\n} from '../util/script_detection';\nimport {findPoleOfInaccessibility} from '../util/find_pole_of_inaccessibility';\nimport {EXTENT} from '../data/extent';\nimport {SymbolBucket} from '../data/bucket/symbol_bucket';\nimport {EvaluationParameters} from '../style/evaluation_parameters';\nimport {SIZE_PACK_FACTOR, MAX_PACKED_SIZE, MAX_GLYPH_ICON_SIZE} from './symbol_size';\nimport ONE_EM from './one_em';\nimport type {CanonicalTileID} from '../source/tile_id';\nimport type {Shaping, PositionedIcon, TextJustify} from './shaping';\nimport type {CollisionBoxArray, TextAnchorOffsetArray} from '../data/array_types.g';\nimport type {SymbolFeature} from '../data/bucket/symbol_bucket';\nimport type {StyleImage} from '../style/style_image';\nimport type {StyleGlyph} from '../style/style_glyph';\nimport type {SymbolStyleLayer} from '../style/style_layer/symbol_style_layer';\nimport type {ImagePosition} from '../render/image_atlas';\nimport type {GlyphPosition} from '../render/glyph_atlas';\nimport type {PossiblyEvaluatedPropertyValue} from '../style/properties';\n\nimport Point from '@mapbox/point-geometry';\nimport murmur3 from 'murmurhash-js';\nimport {getIconPadding, SymbolPadding} from '../style/style_layer/symbol_style_layer';\nimport {VariableAnchorOffsetCollection, classifyRings} from '@maplibre/maplibre-gl-style-spec';\nimport {getTextVariableAnchorOffset, evaluateVariableOffset, INVALID_TEXT_OFFSET, TextAnchor, TextAnchorEnum} from '../style/style_layer/variable_text_anchor';\n\n// The symbol layout process needs `text-size` evaluated at up to five different zoom levels, and\n// `icon-size` at up to three:\n//\n// 1. `text-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `text-size`\n// expressions, and to calculate the box dimensions for icon-text-fit.\n// 2. `icon-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `icon-size`\n// expressions.\n// 3. `text-size` and `icon-size` at the zoom level of the bucket, plus one. Used to calculate collision boxes.\n// 4. `text-size` at zoom level 18. Used for something line-symbol-placement-related.\n// 5. For composite `*-size` expressions: two zoom levels of curve stops that \"cover\" the zoom level of the\n// bucket. These go into a vertex buffer and are used by the shader to interpolate the size at render time.\n//\n// (1) and (2) are stored in `bucket.layers[0].layout`. The remainder are below.\n//\ntype Sizes = {\n layoutTextSize: PossiblyEvaluatedPropertyValue; // (3),\n layoutIconSize: PossiblyEvaluatedPropertyValue; // (3),\n textMaxSize: PossiblyEvaluatedPropertyValue; // (4),\n compositeTextSizes: [PossiblyEvaluatedPropertyValue, PossiblyEvaluatedPropertyValue]; // (5),\n compositeIconSizes: [PossiblyEvaluatedPropertyValue, PossiblyEvaluatedPropertyValue]; // (5)\n};\n\ntype ShapedTextOrientations = {\n vertical: Shaping | false;\n horizontal: Record;\n};\n\nexport function performSymbolLayout(args: {\n bucket: SymbolBucket;\n glyphMap: {\n [_: string]: {\n [x: number]: StyleGlyph;\n };\n };\n glyphPositions: {\n [_: string]: {\n [x: number]: GlyphPosition;\n };\n };\n imageMap: {[_: string]: StyleImage};\n imagePositions: {[_: string]: ImagePosition};\n showCollisionBoxes: boolean;\n canonical: CanonicalTileID;\n}) {\n args.bucket.createArrays();\n\n const tileSize = 512 * args.bucket.overscaling;\n args.bucket.tilePixelRatio = EXTENT / tileSize;\n args.bucket.compareText = {};\n args.bucket.iconsNeedLinear = false;\n\n const layer = args.bucket.layers[0];\n const layout = layer.layout;\n const unevaluatedLayoutValues = layer._unevaluatedLayout._values;\n\n const sizes: Sizes = {\n // Filled in below, if *SizeData.kind is 'composite'\n // compositeIconSizes: undefined,\n // compositeTextSizes: undefined,\n layoutIconSize: unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical),\n layoutTextSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical),\n textMaxSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18))\n } as Sizes;\n\n if (args.bucket.textSizeData.kind === 'composite') {\n const {minZoom, maxZoom} = args.bucket.textSizeData;\n sizes.compositeTextSizes = [\n unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical),\n unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical)\n ];\n }\n\n if (args.bucket.iconSizeData.kind === 'composite') {\n const {minZoom, maxZoom} = args.bucket.iconSizeData;\n sizes.compositeIconSizes = [\n unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical),\n unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical)\n ];\n }\n\n const lineHeight = layout.get('text-line-height') * ONE_EM;\n const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point';\n const keepUpright = layout.get('text-keep-upright');\n const textSize = layout.get('text-size');\n\n for (const feature of args.bucket.features) {\n const fontstack = layout.get('text-font').evaluate(feature, {}, args.canonical).join(',');\n const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, args.canonical);\n const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, args.canonical);\n const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, args.canonical);\n\n const shapedTextOrientations: ShapedTextOrientations = {\n horizontal: {} as Record,\n vertical: undefined\n };\n const text = feature.text;\n let textOffset: [number, number] = [0, 0];\n if (text) {\n const unformattedText = text.toString();\n const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, args.canonical) * ONE_EM;\n const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0;\n\n const textAnchor = layout.get('text-anchor').evaluate(feature, {}, args.canonical);\n const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, args.canonical);\n\n if (!variableAnchorOffset) {\n const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, args.canonical);\n // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector\n // is calculated at placement time instead of layout time\n if (radialOffset) {\n // The style spec says don't use `text-offset` and `text-radial-offset` together\n // but doesn't actually specify what happens if you use both. We go with the radial offset.\n textOffset = evaluateVariableOffset(textAnchor, [radialOffset * ONE_EM, INVALID_TEXT_OFFSET]);\n } else {\n textOffset = (layout.get('text-offset').evaluate(feature, {}, args.canonical).map(t => t * ONE_EM) as [number, number]);\n }\n }\n\n let textJustify = textAlongLine ?\n 'center' :\n layout.get('text-justify').evaluate(feature, {}, args.canonical);\n\n const symbolPlacement = layout.get('symbol-placement');\n const maxWidth = symbolPlacement === 'point' ?\n layout.get('text-max-width').evaluate(feature, {}, args.canonical) * ONE_EM :\n Infinity;\n\n const addVerticalShapingForPointLabelIfNeeded = () => {\n if (args.bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) {\n // Vertical POI label placement is meant to be used for scripts that support vertical\n // writing mode, thus, default left justification is used. If Latin\n // scripts would need to be supported, this should take into account other justifications.\n shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor,\n 'left', spacingIfAllowed, textOffset, WritingMode.vertical, true, layoutTextSize, layoutTextSizeThisZoom);\n }\n };\n\n // If this layer uses text-variable-anchor, generate shapings for all justification possibilities.\n if (!textAlongLine && variableAnchorOffset) {\n const justifications = new Set();\n\n if (textJustify === 'auto') {\n for (let i = 0; i < variableAnchorOffset.values.length; i += 2) {\n justifications.add(getAnchorJustification(variableAnchorOffset.values[i] as TextAnchor));\n }\n } else {\n justifications.add(textJustify);\n }\n\n let singleLine = false;\n for (const justification of justifications) {\n if (shapedTextOrientations.horizontal[justification]) continue;\n if (singleLine) {\n // If the shaping for the first justification was only a single line, we\n // can re-use it for the other justifications\n shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0];\n } else {\n // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply\n // the offsets for the anchor in the placement step.\n const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, 'center',\n justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom);\n if (shaping) {\n shapedTextOrientations.horizontal[justification] = shaping;\n singleLine = shaping.positionedLines.length === 1;\n }\n }\n }\n\n addVerticalShapingForPointLabelIfNeeded();\n } else {\n if (textJustify === 'auto') {\n textJustify = getAnchorJustification(textAnchor);\n }\n\n // Horizontal point or line label.\n const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed,\n textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom);\n if (shaping) shapedTextOrientations.horizontal[textJustify] = shaping;\n\n // Vertical point label (if allowVerticalPlacement is enabled).\n addVerticalShapingForPointLabelIfNeeded();\n\n // Verticalized line label.\n if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) {\n shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify,\n spacingIfAllowed, textOffset, WritingMode.vertical, false, layoutTextSize, layoutTextSizeThisZoom);\n }\n }\n }\n\n let shapedIcon;\n let isSDFIcon = false;\n if (feature.icon && feature.icon.name) {\n const image = args.imageMap[feature.icon.name];\n if (image) {\n shapedIcon = shapeIcon(\n args.imagePositions[feature.icon.name],\n layout.get('icon-offset').evaluate(feature, {}, args.canonical),\n layout.get('icon-anchor').evaluate(feature, {}, args.canonical));\n // null/undefined SDF property treated same as default (false)\n isSDFIcon = !!image.sdf;\n if (args.bucket.sdfIcons === undefined) {\n args.bucket.sdfIcons = isSDFIcon;\n } else if (args.bucket.sdfIcons !== isSDFIcon) {\n warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer');\n }\n if (image.pixelRatio !== args.bucket.pixelRatio) {\n args.bucket.iconsNeedLinear = true;\n } else if (layout.get('icon-rotate').constantOr(1) !== 0) {\n args.bucket.iconsNeedLinear = true;\n }\n }\n }\n\n const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical;\n args.bucket.iconsInText = shapedText ? shapedText.iconsInText : false;\n if (shapedText || shapedIcon) {\n addFeature(args.bucket, feature, shapedTextOrientations, shapedIcon, args.imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, args.canonical);\n }\n }\n\n if (args.showCollisionBoxes) {\n args.bucket.generateCollisionDebugBuffers();\n }\n}\n\n// Choose the justification that matches the direction of the TextAnchor\nexport function getAnchorJustification(anchor: TextAnchor): TextJustify {\n switch (anchor) {\n case 'right':\n case 'top-right':\n case 'bottom-right':\n return 'right';\n case 'left':\n case 'top-left':\n case 'bottom-left':\n return 'left';\n }\n return 'center';\n}\n\n/**\n * Given a feature and its shaped text and icon data, add a 'symbol\n * instance' for each _possible_ placement of the symbol feature.\n * (At render timePlaceSymbols#place() selects which of these instances to\n * show or hide based on collisions with symbols in other layers.)\n */\nfunction addFeature(bucket: SymbolBucket,\n feature: SymbolFeature,\n shapedTextOrientations: ShapedTextOrientations,\n shapedIcon: PositionedIcon,\n imageMap: {[_: string]: StyleImage},\n sizes: Sizes,\n layoutTextSize: number,\n layoutIconSize: number,\n textOffset: [number, number],\n isSDFIcon: boolean,\n canonical: CanonicalTileID) {\n // To reduce the number of labels that jump around when zooming we need\n // to use a text-size value that is the same for all zoom levels.\n // bucket calculates text-size at a high zoom level so that all tiles can\n // use the same value when calculating anchor positions.\n let textMaxSize = sizes.textMaxSize.evaluate(feature, {});\n if (textMaxSize === undefined) {\n textMaxSize = layoutTextSize;\n }\n const layout = bucket.layers[0].layout;\n const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical);\n const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal);\n const glyphSize = 24,\n fontScale = layoutTextSize / glyphSize,\n textBoxScale = bucket.tilePixelRatio * fontScale,\n textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize,\n iconBoxScale = bucket.tilePixelRatio * layoutIconSize,\n symbolMinDistance = bucket.tilePixelRatio * layout.get('symbol-spacing'),\n textPadding = layout.get('text-padding') * bucket.tilePixelRatio,\n iconPadding = getIconPadding(layout, feature, canonical, bucket.tilePixelRatio),\n textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI,\n textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point',\n iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point',\n symbolPlacement = layout.get('symbol-placement'),\n textRepeatDistance = symbolMinDistance / 2;\n\n const iconTextFit = layout.get('icon-text-fit');\n let verticallyShapedIcon;\n // Adjust shaped icon size when icon-text-fit is used.\n if (shapedIcon && iconTextFit !== 'none') {\n if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {\n verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit,\n layout.get('icon-text-fit-padding'), iconOffset, fontScale);\n }\n if (defaultHorizontalShaping) {\n shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit,\n layout.get('icon-text-fit-padding'), iconOffset, fontScale);\n }\n }\n\n const addSymbolAtAnchor = (line, anchor) => {\n if (anchor.x < 0 || anchor.x >= EXTENT || anchor.y < 0 || anchor.y >= EXTENT) {\n // Symbol layers are drawn across tile boundaries, We filter out symbols\n // outside our tile boundaries (which may be included in vector tile buffers)\n // to prevent double-drawing symbols.\n return;\n }\n addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0],\n bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index,\n textBoxScale, [textPadding, textPadding, textPadding, textPadding], textAlongLine, textOffset,\n iconBoxScale, iconPadding, iconAlongLine, iconOffset,\n feature, sizes, isSDFIcon, canonical, layoutTextSize);\n };\n\n if (symbolPlacement === 'line') {\n for (const line of clipLine(feature.geometry, 0, 0, EXTENT, EXTENT)) {\n const anchors = getAnchors(\n line,\n symbolMinDistance,\n textMaxAngle,\n shapedTextOrientations.vertical || defaultHorizontalShaping,\n shapedIcon,\n glyphSize,\n textMaxBoxScale,\n bucket.overscaling,\n EXTENT\n );\n for (const anchor of anchors) {\n const shapedText = defaultHorizontalShaping;\n if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) {\n addSymbolAtAnchor(line, anchor);\n }\n }\n }\n } else if (symbolPlacement === 'line-center') {\n // No clipping, multiple lines per feature are allowed\n // \"lines\" with only one point are ignored as in clipLines\n for (const line of feature.geometry) {\n if (line.length > 1) {\n const anchor = getCenterAnchor(\n line,\n textMaxAngle,\n shapedTextOrientations.vertical || defaultHorizontalShaping,\n shapedIcon,\n glyphSize,\n textMaxBoxScale);\n if (anchor) {\n addSymbolAtAnchor(line, anchor);\n }\n }\n }\n } else if (feature.type === 'Polygon') {\n for (const polygon of classifyRings(feature.geometry, 0)) {\n // 16 here represents 2 pixels\n const poi = findPoleOfInaccessibility(polygon, 16);\n addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0));\n }\n } else if (feature.type === 'LineString') {\n // https://github.com/mapbox/mapbox-gl-js/issues/3808\n for (const line of feature.geometry) {\n addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0));\n }\n } else if (feature.type === 'Point') {\n for (const points of feature.geometry) {\n for (const point of points) {\n addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0));\n }\n }\n }\n}\n\nfunction addTextVariableAnchorOffsets(textAnchorOffsets: TextAnchorOffsetArray, variableAnchorOffset: VariableAnchorOffsetCollection): [number, number] {\n const startIndex = textAnchorOffsets.length;\n const values = variableAnchorOffset?.values;\n\n if (values?.length > 0) {\n for (let i = 0; i < values.length; i += 2) {\n const anchor = TextAnchorEnum[values[i] as TextAnchor];\n const offset = values[i + 1] as [number, number];\n\n textAnchorOffsets.emplaceBack(anchor, offset[0], offset[1]);\n }\n }\n\n return [startIndex, textAnchorOffsets.length];\n}\n\nfunction addTextVertices(bucket: SymbolBucket,\n anchor: Point,\n shapedText: Shaping,\n imageMap: {[_: string]: StyleImage},\n layer: SymbolStyleLayer,\n textAlongLine: boolean,\n feature: SymbolFeature,\n textOffset: [number, number],\n lineArray: {\n lineStartIndex: number;\n lineLength: number;\n },\n writingMode: WritingMode,\n placementTypes: Array<'vertical' | 'center' | 'left' | 'right'>,\n placedTextSymbolIndices: {[_: string]: number},\n placedIconIndex: number,\n sizes: Sizes,\n canonical: CanonicalTileID) {\n const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset,\n layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement);\n\n const sizeData = bucket.textSizeData;\n let textSizeData = null;\n\n if (sizeData.kind === 'source') {\n textSizeData = [\n SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {})\n ];\n if (textSizeData[0] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"text-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"text-size\".`);\n }\n } else if (sizeData.kind === 'composite') {\n textSizeData = [\n SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical),\n SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical)\n ];\n if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"text-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"text-size\".`);\n }\n }\n\n bucket.addSymbols(\n bucket.text,\n glyphQuads,\n textSizeData,\n textOffset,\n textAlongLine,\n feature,\n writingMode,\n anchor,\n lineArray.lineStartIndex,\n lineArray.lineLength,\n placedIconIndex,\n canonical);\n\n // The placedSymbolArray is used at render time in drawTileSymbols\n // These indices allow access to the array at collision detection time\n for (const placementType of placementTypes) {\n placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1;\n }\n\n return glyphQuads.length * 4;\n}\n\nfunction getDefaultHorizontalShaping(\n horizontalShaping: Record\n): Shaping | null {\n // We don't care which shaping we get because this is used for collision purposes\n // and all the justifications have the same collision box\n for (const justification in horizontalShaping) {\n return horizontalShaping[justification];\n }\n return null;\n}\n\n/**\n * Add a single label & icon placement.\n */\nfunction addSymbol(bucket: SymbolBucket,\n anchor: Anchor,\n line: Array,\n shapedTextOrientations: ShapedTextOrientations,\n shapedIcon: PositionedIcon | void,\n imageMap: {[_: string]: StyleImage},\n verticallyShapedIcon: PositionedIcon | void,\n layer: SymbolStyleLayer,\n collisionBoxArray: CollisionBoxArray,\n featureIndex: number,\n sourceLayerIndex: number,\n bucketIndex: number,\n textBoxScale: number,\n textPadding: SymbolPadding,\n textAlongLine: boolean,\n textOffset: [number, number],\n iconBoxScale: number,\n iconPadding: SymbolPadding,\n iconAlongLine: boolean,\n iconOffset: [number, number],\n feature: SymbolFeature,\n sizes: Sizes,\n isSDFIcon: boolean,\n canonical: CanonicalTileID,\n layoutTextSize: number) {\n\n const lineArray = bucket.addToLineVertexArray(anchor, line);\n\n let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature;\n\n let numIconVertices = 0;\n let numVerticalIconVertices = 0;\n let numHorizontalGlyphVertices = 0;\n let numVerticalGlyphVertices = 0;\n let placedIconSymbolIndex = -1;\n let verticalPlacedIconSymbolIndex = -1;\n const placedTextSymbolIndices: {[k: string]: number} = {};\n let key = murmur3('');\n\n if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {\n const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\n const verticalTextRotation = textRotation + 90.0;\n const verticalShaping = shapedTextOrientations.vertical;\n verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation);\n\n if (verticallyShapedIcon) {\n verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation);\n }\n }\n\n //Place icon first, so text can have a reference to its index in the placed symbol array.\n //Text symbols can lazily shift at render-time because of variable anchor placement.\n //If the style specifies an `icon-text-fit` then the icon would have to shift along with it.\n // For more info check `updateVariableAnchors` in `draw_symbol.js` .\n if (shapedIcon) {\n const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {});\n const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none';\n const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit);\n const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined;\n iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/false, iconRotate);\n\n numIconVertices = iconQuads.length * 4;\n\n const sizeData = bucket.iconSizeData;\n let iconSizeData = null;\n\n if (sizeData.kind === 'source') {\n iconSizeData = [\n SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {})\n ];\n if (iconSizeData[0] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"icon-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"icon-size\".`);\n }\n } else if (sizeData.kind === 'composite') {\n iconSizeData = [\n SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical),\n SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical)\n ];\n if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"icon-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"icon-size\".`);\n }\n }\n\n bucket.addSymbols(\n bucket.icon,\n iconQuads,\n iconSizeData,\n iconOffset,\n iconAlongLine,\n feature,\n WritingMode.none,\n anchor,\n lineArray.lineStartIndex,\n lineArray.lineLength,\n // The icon itself does not have an associated symbol since the text isn't placed yet\n -1, canonical);\n\n placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;\n\n if (verticalIconQuads) {\n numVerticalIconVertices = verticalIconQuads.length * 4;\n\n bucket.addSymbols(\n bucket.icon,\n verticalIconQuads,\n iconSizeData,\n iconOffset,\n iconAlongLine,\n feature,\n WritingMode.vertical,\n anchor,\n lineArray.lineStartIndex,\n lineArray.lineLength,\n // The icon itself does not have an associated symbol since the text isn't placed yet\n -1, canonical);\n\n verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;\n }\n }\n\n const justifications = Object.keys(shapedTextOrientations.horizontal) as TextJustify[];\n for (const justification of justifications) {\n const shaping = shapedTextOrientations.horizontal[justification];\n\n if (!textCollisionFeature) {\n key = murmur3(shaping.text);\n const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\n // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature\n // We're counting on all versions having similar dimensions\n textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate);\n }\n\n const singleLine = shaping.positionedLines.length === 1;\n numHorizontalGlyphVertices += addTextVertices(\n bucket, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, lineArray,\n shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly,\n singleLine ? justifications : [justification],\n placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical);\n\n if (singleLine) {\n break;\n }\n }\n\n if (shapedTextOrientations.vertical) {\n numVerticalGlyphVertices += addTextVertices(\n bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature,\n textOffset, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical);\n }\n\n const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n // Check if runtime collision circles should be used for any of the collision features.\n // It is enough to choose the tallest feature shape as circles are always placed on a line.\n // All measurements are in glyph metrics and later converted into pixels using proper font size \"layoutTextSize\"\n let collisionCircleDiameter = -1;\n\n const getCollisionCircleHeight = (feature: CollisionFeature, prevHeight: number): number => {\n if (feature && feature.circleDiameter)\n return Math.max(feature.circleDiameter, prevHeight);\n return prevHeight;\n };\n\n collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter);\n const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0;\n\n // Convert circle collision height into pixels\n if (useRuntimeCollisionCircles)\n collisionCircleDiameter *= layoutTextSize / ONE_EM;\n\n if (bucket.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS) warnOnce(\n 'Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907'\n );\n\n if (feature.sortKey !== undefined) {\n bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey as number);\n }\n\n const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, canonical);\n const [textAnchorOffsetStartIndex, textAnchorOffsetEndIndex] = addTextVariableAnchorOffsets(bucket.textAnchorOffsets, variableAnchorOffset);\n\n bucket.symbolInstances.emplaceBack(\n anchor.x,\n anchor.y,\n placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1,\n placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1,\n placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1,\n placedTextSymbolIndices.vertical || -1,\n placedIconSymbolIndex,\n verticalPlacedIconSymbolIndex,\n key,\n textBoxStartIndex,\n textBoxEndIndex,\n verticalTextBoxStartIndex,\n verticalTextBoxEndIndex,\n iconBoxStartIndex,\n iconBoxEndIndex,\n verticalIconBoxStartIndex,\n verticalIconBoxEndIndex,\n featureIndex,\n numHorizontalGlyphVertices,\n numVerticalGlyphVertices,\n numIconVertices,\n numVerticalIconVertices,\n useRuntimeCollisionCircles,\n 0,\n textBoxScale,\n collisionCircleDiameter,\n textAnchorOffsetStartIndex,\n textAnchorOffsetEndIndex);\n}\n\nfunction anchorIsTooClose(bucket: SymbolBucket, text: string, repeatDistance: number, anchor: Point) {\n const compareText = bucket.compareText;\n if (!(text in compareText)) {\n compareText[text] = [];\n } else {\n const otherAnchors = compareText[text];\n for (let k = otherAnchors.length - 1; k >= 0; k--) {\n if (anchor.dist(otherAnchors[k]) < repeatDistance) {\n // If it's within repeatDistance of one anchor, stop looking\n return true;\n }\n }\n }\n // If anchor is not within repeatDistance of any other anchor, add to array\n compareText[text].push(anchor);\n return false;\n}\n","import type {Tile} from '../../source/tile';\nimport {pixelsToTileUnits} from '../../source/pixels_to_tile_units';\nimport type {PointProjection} from '../../symbol/projection';\n\n/**\n * A greatly reduced version of the `Projection` interface from the globe branch,\n * used to port symbol bugfixes over to the main branch. Will be replaced with\n * the proper interface once globe is merged.\n */\nexport type Projection = {\n useSpecialProjectionForSymbols: boolean;\n isOccluded(_x, _y, _t): boolean;\n projectTileCoordinates(_x, _y, _t, _ele): PointProjection;\n getPitchedTextCorrection(_transform, _anchor, _tile): number;\n translatePosition(transform: { angle: number; zoom: number }, tile: Tile, translate: [number, number], translateAnchor: 'map' | 'viewport'): [number, number];\n getCircleRadiusCorrection(tr: any): number;\n};\n\nexport function createProjection(): Projection {\n return {\n isOccluded(_x: any, _y: any, _t: any) {\n return false;\n },\n getPitchedTextCorrection(_transform: any, _anchor: any, _tile: any) {\n return 1.0;\n },\n get useSpecialProjectionForSymbols() { return false; },\n projectTileCoordinates(_x, _y, _t, _ele) {\n // This function should only be used when useSpecialProjectionForSymbols is set to true.\n throw new Error('Not implemented.');\n },\n translatePosition(transform, tile, translate, translateAnchor) {\n return translatePosition(transform, tile, translate, translateAnchor);\n },\n getCircleRadiusCorrection(_: any) {\n return 1.0;\n }\n };\n}\n\n/**\n * Returns a translation in tile units that correctly incorporates the view angle and the *-translate and *-translate-anchor properties.\n * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units.\n *\n * Temporarily imported from globe branch.\n */\nfunction translatePosition(\n transform: { angle: number; zoom: number },\n tile: Tile,\n translate: [number, number],\n translateAnchor: 'map' | 'viewport',\n inViewportPixelUnitsUnits: boolean = false\n): [number, number] {\n if (!translate[0] && !translate[1]) return [0, 0];\n\n const angle = inViewportPixelUnitsUnits ?\n (translateAnchor === 'map' ? transform.angle : 0) :\n (translateAnchor === 'viewport' ? -transform.angle : 0);\n\n if (angle) {\n const sinA = Math.sin(angle);\n const cosA = Math.cos(angle);\n translate = [\n translate[0] * cosA - translate[1] * sinA,\n translate[0] * sinA + translate[1] * cosA\n ];\n }\n\n return [\n inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], transform.zoom),\n inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], transform.zoom)];\n}\n","import {browser} from '../util/browser';\n\nimport {Placement} from '../symbol/placement';\n\nimport type {Transform} from '../geo/transform';\nimport type {StyleLayer} from './style_layer';\nimport type {SymbolStyleLayer} from './style_layer/symbol_style_layer';\nimport type {Tile} from '../source/tile';\nimport type {BucketPart} from '../symbol/placement';\nimport {Terrain} from '../render/terrain';\nimport {createProjection} from '../geo/projection/projection';\n\nclass LayerPlacement {\n _sortAcrossTiles: boolean;\n _currentTileIndex: number;\n _currentPartIndex: number;\n _seenCrossTileIDs: {\n [k in string | number]: boolean;\n };\n _bucketParts: Array;\n\n constructor(styleLayer: SymbolStyleLayer) {\n this._sortAcrossTiles = styleLayer.layout.get('symbol-z-order') !== 'viewport-y' &&\n !styleLayer.layout.get('symbol-sort-key').isConstant();\n\n this._currentTileIndex = 0;\n this._currentPartIndex = 0;\n this._seenCrossTileIDs = {};\n this._bucketParts = [];\n }\n\n continuePlacement(tiles: Array, placement: Placement, showCollisionBoxes: boolean, styleLayer: StyleLayer, shouldPausePlacement: () => boolean) {\n\n const bucketParts = this._bucketParts;\n\n while (this._currentTileIndex < tiles.length) {\n const tile = tiles[this._currentTileIndex];\n placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles);\n\n this._currentTileIndex++;\n if (shouldPausePlacement()) {\n return true;\n }\n }\n\n if (this._sortAcrossTiles) {\n this._sortAcrossTiles = false;\n bucketParts.sort((a, b) => (a.sortKey as any as number) - (b.sortKey as any as number));\n }\n\n while (this._currentPartIndex < bucketParts.length) {\n const bucketPart = bucketParts[this._currentPartIndex];\n placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes);\n\n this._currentPartIndex++;\n if (shouldPausePlacement()) {\n return true;\n }\n }\n return false;\n }\n}\n\nexport class PauseablePlacement {\n placement: Placement;\n _done: boolean;\n _currentPlacementIndex: number;\n _forceFullPlacement: boolean;\n _showCollisionBoxes: boolean;\n _inProgressLayer: LayerPlacement;\n\n constructor(\n transform: Transform,\n terrain: Terrain,\n order: Array,\n forceFullPlacement: boolean,\n showCollisionBoxes: boolean,\n fadeDuration: number,\n crossSourceCollisions: boolean,\n prevPlacement?: Placement\n ) {\n this.placement = new Placement(transform, createProjection(), terrain, fadeDuration, crossSourceCollisions, prevPlacement);\n this._currentPlacementIndex = order.length - 1;\n this._forceFullPlacement = forceFullPlacement;\n this._showCollisionBoxes = showCollisionBoxes;\n this._done = false;\n }\n\n isDone() {\n return this._done;\n }\n\n continuePlacement(\n order: Array,\n layers: {[_: string]: StyleLayer},\n layerTiles: {[_: string]: Array}\n ) {\n const startTime = browser.now();\n\n const shouldPausePlacement = () => {\n return this._forceFullPlacement ? false : (browser.now() - startTime) > 2;\n };\n\n while (this._currentPlacementIndex >= 0) {\n const layerId = order[this._currentPlacementIndex];\n const layer = layers[layerId];\n const placementZoom = this.placement.collisionIndex.transform.zoom;\n if (layer.type === 'symbol' &&\n (!layer.minzoom || layer.minzoom <= placementZoom) &&\n (!layer.maxzoom || layer.maxzoom > placementZoom)) {\n\n if (!this._inProgressLayer) {\n this._inProgressLayer = new LayerPlacement(layer as any as SymbolStyleLayer);\n }\n\n const pausePlacement = this._inProgressLayer.continuePlacement(layerTiles[layer.source], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement);\n\n if (pausePlacement) {\n // We didn't finish placing all layers within 2ms,\n // but we can keep rendering with a partial placement\n // We'll resume here on the next frame\n return;\n }\n\n delete this._inProgressLayer;\n }\n\n this._currentPlacementIndex--;\n }\n\n this._done = true;\n }\n\n commit(now: number) {\n this.placement.commit(now);\n return this.placement;\n }\n}\n","\nconst ARRAY_TYPES = [\n Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,\n Int32Array, Uint32Array, Float32Array, Float64Array\n];\n\n/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */\n\nconst VERSION = 1; // serialized format version\nconst HEADER_SIZE = 8;\n\nexport default class KDBush {\n\n /**\n * Creates an index from raw `ArrayBuffer` data.\n * @param {ArrayBuffer} data\n */\n static from(data) {\n if (!(data instanceof ArrayBuffer)) {\n throw new Error('Data must be an instance of ArrayBuffer.');\n }\n const [magic, versionAndType] = new Uint8Array(data, 0, 2);\n if (magic !== 0xdb) {\n throw new Error('Data does not appear to be in a KDBush format.');\n }\n const version = versionAndType >> 4;\n if (version !== VERSION) {\n throw new Error(`Got v${version} data when expected v${VERSION}.`);\n }\n const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];\n if (!ArrayType) {\n throw new Error('Unrecognized array type.');\n }\n const [nodeSize] = new Uint16Array(data, 2, 1);\n const [numItems] = new Uint32Array(data, 4, 1);\n\n return new KDBush(numItems, nodeSize, ArrayType, data);\n }\n\n /**\n * Creates an index that will hold a given number of items.\n * @param {number} numItems\n * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).\n * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).\n * @param {ArrayBuffer} [data] (For internal use only)\n */\n constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) {\n if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`);\n\n this.numItems = +numItems;\n this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);\n this.ArrayType = ArrayType;\n this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;\n\n const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);\n const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;\n const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;\n const padCoords = (8 - idsByteSize % 8) % 8;\n\n if (arrayTypeIndex < 0) {\n throw new Error(`Unexpected typed array class: ${ArrayType}.`);\n }\n\n if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer\n this.data = data;\n this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);\n this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = numItems * 2;\n this._finished = true;\n } else { // initialize a new index\n this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);\n this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);\n this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = 0;\n this._finished = false;\n\n // set header\n new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);\n new Uint16Array(this.data, 2, 1)[0] = nodeSize;\n new Uint32Array(this.data, 4, 1)[0] = numItems;\n }\n }\n\n /**\n * Add a point to the index.\n * @param {number} x\n * @param {number} y\n * @returns {number} An incremental index associated with the added item (starting from `0`).\n */\n add(x, y) {\n const index = this._pos >> 1;\n this.ids[index] = index;\n this.coords[this._pos++] = x;\n this.coords[this._pos++] = y;\n return index;\n }\n\n /**\n * Perform indexing of the added points.\n */\n finish() {\n const numAdded = this._pos >> 1;\n if (numAdded !== this.numItems) {\n throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);\n }\n // kd-sort both arrays for efficient search\n sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);\n\n this._finished = true;\n return this;\n }\n\n /**\n * Search the index for items within a given bounding box.\n * @param {number} minX\n * @param {number} minY\n * @param {number} maxX\n * @param {number} maxY\n * @returns {number[]} An array of indices correponding to the found items.\n */\n range(minX, minY, maxX, maxY) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n const {ids, coords, nodeSize} = this;\n const stack = [0, ids.length - 1, 0];\n const result = [];\n\n // recursively search for items in range in the kd-sorted arrays\n while (stack.length) {\n const axis = stack.pop() || 0;\n const right = stack.pop() || 0;\n const left = stack.pop() || 0;\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n const x = coords[2 * i];\n const y = coords[2 * i + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);\n }\n continue;\n }\n\n // otherwise find the middle index\n const m = (left + right) >> 1;\n\n // include the middle item if it's in range\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);\n\n // queue search in halves that intersect the query\n if (axis === 0 ? minX <= x : minY <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(1 - axis);\n }\n if (axis === 0 ? maxX >= x : maxY >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(1 - axis);\n }\n }\n\n return result;\n }\n\n /**\n * Search the index for items within a given radius.\n * @param {number} qx\n * @param {number} qy\n * @param {number} r Query radius.\n * @returns {number[]} An array of indices correponding to the found items.\n */\n within(qx, qy, r) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n const {ids, coords, nodeSize} = this;\n const stack = [0, ids.length - 1, 0];\n const result = [];\n const r2 = r * r;\n\n // recursively search for items within radius in the kd-sorted arrays\n while (stack.length) {\n const axis = stack.pop() || 0;\n const right = stack.pop() || 0;\n const left = stack.pop() || 0;\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);\n }\n continue;\n }\n\n // otherwise find the middle index\n const m = (left + right) >> 1;\n\n // include the middle item if it's in range\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);\n\n // queue search in halves that intersect the query\n if (axis === 0 ? qx - r <= x : qy - r <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(1 - axis);\n }\n if (axis === 0 ? qx + r >= x : qy + r >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(1 - axis);\n }\n }\n\n return result;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {InstanceType} coords\n * @param {number} nodeSize\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction sort(ids, coords, nodeSize, left, right, axis) {\n if (right - left <= nodeSize) return;\n\n const m = (left + right) >> 1; // middle index\n\n // sort ids and coords around the middle index so that the halves lie\n // either left/right or top/bottom correspondingly (taking turns)\n select(ids, coords, m, left, right, axis);\n\n // recursively kd-sort first half and second half on the opposite axis\n sort(ids, coords, nodeSize, left, m - 1, 1 - axis);\n sort(ids, coords, nodeSize, m + 1, right, 1 - axis);\n}\n\n/**\n * Custom Floyd-Rivest selection algorithm: sort ids and coords so that\n * [left..k-1] items are smaller than k-th item (on either x or y axis)\n * @param {Uint16Array | Uint32Array} ids\n * @param {InstanceType} coords\n * @param {number} k\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction select(ids, coords, k, left, right, axis) {\n\n while (right > left) {\n if (right - left > 600) {\n const n = right - left + 1;\n const m = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n select(ids, coords, k, newLeft, newRight, axis);\n }\n\n const t = coords[2 * k + axis];\n let i = left;\n let j = right;\n\n swapItem(ids, coords, left, k);\n if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);\n\n while (i < j) {\n swapItem(ids, coords, i, j);\n i++;\n j--;\n while (coords[2 * i + axis] < t) i++;\n while (coords[2 * j + axis] > t) j--;\n }\n\n if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);\n else {\n j++;\n swapItem(ids, coords, j, right);\n }\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {InstanceType} coords\n * @param {number} i\n * @param {number} j\n */\nfunction swapItem(ids, coords, i, j) {\n swap(ids, i, j);\n swap(coords, 2 * i, 2 * j);\n swap(coords, 2 * i + 1, 2 * j + 1);\n}\n\n/**\n * @param {InstanceType} arr\n * @param {number} i\n * @param {number} j\n */\nfunction swap(arr, i, j) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\n/**\n * @param {number} ax\n * @param {number} ay\n * @param {number} bx\n * @param {number} by\n */\nfunction sqDist(ax, ay, bx, by) {\n const dx = ax - bx;\n const dy = ay - by;\n return dx * dx + dy * dy;\n}\n","import KDBush from 'kdbush';\nimport {EXTENT} from '../data/extent';\n\nimport {SymbolInstanceArray} from '../data/array_types.g';\n\nimport type {SymbolInstance} from '../data/array_types.g';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport type {SymbolBucket} from '../data/bucket/symbol_bucket';\nimport type {StyleLayer} from '../style/style_layer';\nimport type {Tile} from '../source/tile';\n\n/*\n The CrossTileSymbolIndex generally works on the assumption that\n a conceptual \"unique symbol\" can be identified by the text of\n the label combined with the anchor point. The goal is to assign\n these conceptual \"unique symbols\" a shared crossTileID that can be\n used by Placement to keep fading opacity states consistent and to\n deduplicate labels.\n\n The CrossTileSymbolIndex indexes all the current symbol instances and\n their crossTileIDs. When a symbol bucket gets added or updated, the\n index assigns a crossTileID to each of it's symbol instances by either\n matching it with an existing id or assigning a new one.\n*/\n\n// Round anchor positions to roughly 4 pixel grid\nconst roundingFactor = 512 / EXTENT / 2;\n\nexport const KDBUSH_THRESHHOLD = 128;\n\ninterface SymbolsByKeyEntry {\n index?: KDBush;\n positions?: {x: number; y: number}[];\n crossTileIDs: number[];\n}\n\nclass TileLayerIndex {\n _symbolsByKey: Record = {};\n\n constructor(public tileID: OverscaledTileID, symbolInstances: SymbolInstanceArray, public bucketInstanceId: number) {\n // group the symbolInstances by key\n const symbolInstancesByKey = new Map();\n for (let i = 0; i < symbolInstances.length; i++) {\n const symbolInstance = symbolInstances.get(i);\n const key = symbolInstance.key;\n const instances = symbolInstancesByKey.get(key);\n if (instances) {\n // This tile may have multiple symbol instances with the same key\n // Store each one along with its coordinates\n instances.push(symbolInstance);\n } else {\n symbolInstancesByKey.set(key, [symbolInstance]);\n }\n }\n\n // index the SymbolInstances in this each bucket\n for (const [key, symbols] of symbolInstancesByKey) {\n const positions = symbols.map(symbolInstance => ({x: Math.floor(symbolInstance.anchorX * roundingFactor), y: Math.floor(symbolInstance.anchorY * roundingFactor)}));\n const crossTileIDs = symbols.map(v => v.crossTileID);\n const entry: SymbolsByKeyEntry = {positions, crossTileIDs};\n\n // once we get too many symbols for a given key, it becomes much faster to index it before queries\n if (entry.positions.length > KDBUSH_THRESHHOLD) {\n\n const index = new KDBush(entry.positions.length, 16, Uint16Array);\n for (const {x, y} of entry.positions) index.add(x, y);\n index.finish();\n\n // clear all references to the original positions data\n delete entry.positions;\n entry.index = index;\n }\n\n this._symbolsByKey[key] = entry;\n }\n }\n\n // Converts the coordinates of the input symbol instance into coordinates that be can compared\n // against other symbols in this index. Coordinates are:\n // (1) local-tile-based (so after correction we get x,y values relative to our local anchorX/Y)\n // (2) converted to the z-scale of this TileLayerIndex\n // (3) down-sampled by \"roundingFactor\" from tile coordinate precision in order to be\n // more tolerant of small differences between tiles.\n getScaledCoordinates(symbolInstance: SymbolInstance, childTileID: OverscaledTileID): {x: number; y: number} {\n const {x: localX, y: localY, z: localZ} = this.tileID.canonical;\n const {x, y, z} = childTileID.canonical;\n\n const zDifference = z - localZ;\n const scale = roundingFactor / Math.pow(2, zDifference);\n const xWorld = (x * EXTENT + symbolInstance.anchorX) * scale;\n const yWorld = (y * EXTENT + symbolInstance.anchorY) * scale;\n const xOffset = localX * EXTENT * roundingFactor;\n const yOffset = localY * EXTENT * roundingFactor;\n const result = {\n x: Math.floor(xWorld - xOffset),\n y: Math.floor(yWorld - yOffset)\n };\n\n return result;\n }\n\n findMatches(symbolInstances: SymbolInstanceArray, newTileID: OverscaledTileID, zoomCrossTileIDs: {\n [crossTileID: number]: boolean;\n }) {\n const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z);\n\n for (let i = 0; i < symbolInstances.length; i++) {\n const symbolInstance = symbolInstances.get(i);\n if (symbolInstance.crossTileID) {\n // already has a match, skip\n continue;\n }\n\n const entry = this._symbolsByKey[symbolInstance.key];\n if (!entry) {\n // No symbol with this key in this bucket\n continue;\n }\n\n const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID);\n\n if (entry.index) {\n // Return any symbol with the same keys whose coordinates are within 1\n // grid unit. (with a 4px grid, this covers a 12px by 12px area)\n const indexes = entry.index.range(\n scaledSymbolCoord.x - tolerance,\n scaledSymbolCoord.y - tolerance,\n scaledSymbolCoord.x + tolerance,\n scaledSymbolCoord.y + tolerance).sort();\n\n for (const i of indexes) {\n const crossTileID = entry.crossTileIDs[i];\n\n if (!zoomCrossTileIDs[crossTileID]) {\n // Once we've marked ourselves duplicate against this parent symbol,\n // don't let any other symbols at the same zoom level duplicate against\n // the same parent (see issue #5993)\n zoomCrossTileIDs[crossTileID] = true;\n symbolInstance.crossTileID = crossTileID;\n break;\n }\n }\n } else if (entry.positions) {\n for (let i = 0; i < entry.positions.length; i++) {\n const thisTileSymbol = entry.positions[i];\n const crossTileID = entry.crossTileIDs[i];\n\n // Return any symbol with the same keys whose coordinates are within 1\n // grid unit. (with a 4px grid, this covers a 12px by 12px area)\n if (Math.abs(thisTileSymbol.x - scaledSymbolCoord.x) <= tolerance &&\n Math.abs(thisTileSymbol.y - scaledSymbolCoord.y) <= tolerance &&\n !zoomCrossTileIDs[crossTileID]) {\n // Once we've marked ourselves duplicate against this parent symbol,\n // don't let any other symbols at the same zoom level duplicate against\n // the same parent (see issue #5993)\n zoomCrossTileIDs[crossTileID] = true;\n symbolInstance.crossTileID = crossTileID;\n break;\n }\n }\n }\n }\n }\n\n getCrossTileIDsLists() {\n return Object.values(this._symbolsByKey).map(({crossTileIDs}) => crossTileIDs);\n }\n}\n\nclass CrossTileIDs {\n maxCrossTileID: number;\n constructor() {\n this.maxCrossTileID = 0;\n }\n generate() {\n return ++this.maxCrossTileID;\n }\n}\n\nclass CrossTileSymbolLayerIndex {\n indexes: {\n [zoom in string | number]: {\n [tileId in string | number]: TileLayerIndex;\n };\n };\n usedCrossTileIDs: {\n [zoom in string | number]: {\n [crossTileID: number]: boolean;\n };\n };\n lng: number;\n\n constructor() {\n this.indexes = {};\n this.usedCrossTileIDs = {};\n this.lng = 0;\n }\n\n /*\n * Sometimes when a user pans across the antimeridian the longitude value gets wrapped.\n * To prevent labels from flashing out and in we adjust the tileID values in the indexes\n * so that they match the new wrapped version of the map.\n */\n handleWrapJump(lng: number) {\n const wrapDelta = Math.round((lng - this.lng) / 360);\n if (wrapDelta !== 0) {\n for (const zoom in this.indexes) {\n const zoomIndexes = this.indexes[zoom];\n const newZoomIndex = {};\n for (const key in zoomIndexes) {\n // change the tileID's wrap and add it to a new index\n const index = zoomIndexes[key];\n index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta);\n newZoomIndex[index.tileID.key] = index;\n }\n this.indexes[zoom] = newZoomIndex;\n }\n }\n this.lng = lng;\n }\n\n addBucket(tileID: OverscaledTileID, bucket: SymbolBucket, crossTileIDs: CrossTileIDs) {\n if (this.indexes[tileID.overscaledZ] &&\n this.indexes[tileID.overscaledZ][tileID.key]) {\n if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId ===\n bucket.bucketInstanceId) {\n return false;\n } else {\n // We're replacing this bucket with an updated version\n // Remove the old bucket's \"used crossTileIDs\" now so that\n // the new bucket can claim them.\n // The old index entries themselves stick around until\n // 'removeStaleBuckets' is called.\n this.removeBucketCrossTileIDs(tileID.overscaledZ,\n this.indexes[tileID.overscaledZ][tileID.key]);\n }\n }\n\n for (let i = 0; i < bucket.symbolInstances.length; i++) {\n const symbolInstance = bucket.symbolInstances.get(i);\n symbolInstance.crossTileID = 0;\n }\n\n if (!this.usedCrossTileIDs[tileID.overscaledZ]) {\n this.usedCrossTileIDs[tileID.overscaledZ] = {};\n }\n const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ];\n\n for (const zoom in this.indexes) {\n const zoomIndexes = this.indexes[zoom];\n if (Number(zoom) > tileID.overscaledZ) {\n for (const id in zoomIndexes) {\n const childIndex = zoomIndexes[id];\n if (childIndex.tileID.isChildOf(tileID)) {\n childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);\n }\n }\n } else {\n const parentCoord = tileID.scaledTo(Number(zoom));\n const parentIndex = zoomIndexes[parentCoord.key];\n if (parentIndex) {\n parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);\n }\n }\n }\n\n for (let i = 0; i < bucket.symbolInstances.length; i++) {\n const symbolInstance = bucket.symbolInstances.get(i);\n if (!symbolInstance.crossTileID) {\n // symbol did not match any known symbol, assign a new id\n symbolInstance.crossTileID = crossTileIDs.generate();\n zoomCrossTileIDs[symbolInstance.crossTileID] = true;\n }\n }\n\n if (this.indexes[tileID.overscaledZ] === undefined) {\n this.indexes[tileID.overscaledZ] = {};\n }\n this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId);\n\n return true;\n }\n\n removeBucketCrossTileIDs(zoom: string | number, removedBucket: TileLayerIndex) {\n for (const crossTileIDs of removedBucket.getCrossTileIDsLists()) {\n for (const crossTileID of crossTileIDs) {\n delete this.usedCrossTileIDs[zoom][crossTileID];\n }\n }\n }\n\n removeStaleBuckets(currentIDs: {\n [k in string | number]: boolean;\n }) {\n let tilesChanged = false;\n for (const z in this.indexes) {\n const zoomIndexes = this.indexes[z];\n for (const tileKey in zoomIndexes) {\n if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) {\n this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]);\n delete zoomIndexes[tileKey];\n tilesChanged = true;\n }\n }\n }\n return tilesChanged;\n }\n}\n\nexport class CrossTileSymbolIndex {\n layerIndexes: {[layerId: string]: CrossTileSymbolLayerIndex};\n crossTileIDs: CrossTileIDs;\n maxBucketInstanceId: number;\n bucketsInCurrentPlacement: {[_: number]: boolean};\n\n constructor() {\n this.layerIndexes = {};\n this.crossTileIDs = new CrossTileIDs();\n this.maxBucketInstanceId = 0;\n this.bucketsInCurrentPlacement = {};\n }\n\n addLayer(styleLayer: StyleLayer, tiles: Array, lng: number) {\n let layerIndex = this.layerIndexes[styleLayer.id];\n if (layerIndex === undefined) {\n layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex();\n }\n\n let symbolBucketsChanged = false;\n const currentBucketIDs = {};\n\n layerIndex.handleWrapJump(lng);\n\n for (const tile of tiles) {\n const symbolBucket = (tile.getBucket(styleLayer) as any as SymbolBucket);\n if (!symbolBucket || styleLayer.id !== symbolBucket.layerIds[0])\n continue;\n\n if (!symbolBucket.bucketInstanceId) {\n symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId;\n }\n\n if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) {\n symbolBucketsChanged = true;\n }\n currentBucketIDs[symbolBucket.bucketInstanceId] = true;\n }\n\n if (layerIndex.removeStaleBuckets(currentBucketIDs)) {\n symbolBucketsChanged = true;\n }\n\n return symbolBucketsChanged;\n }\n\n pruneUnusedLayers(usedLayers: Array) {\n const usedLayerMap = {};\n usedLayers.forEach((usedLayer) => {\n usedLayerMap[usedLayer] = true;\n });\n for (const layerId in this.layerIndexes) {\n if (!usedLayerMap[layerId]) {\n delete this.layerIndexes[layerId];\n }\n }\n }\n}\n","import {Event, ErrorEvent, Evented} from '../util/evented';\nimport {StyleLayer} from './style_layer';\nimport {createStyleLayer} from './create_style_layer';\nimport {loadSprite} from './load_sprite';\nimport {ImageManager} from '../render/image_manager';\nimport {GlyphManager} from '../render/glyph_manager';\nimport {Light} from './light';\nimport {Sky} from './sky';\nimport {LineAtlas} from '../render/line_atlas';\nimport {clone, extend, deepEqual, filterObject, mapObject} from '../util/util';\nimport {coerceSpriteToArray} from '../util/style';\nimport {getJSON, getReferrer} from '../util/ajax';\nimport {ResourceType} from '../util/request_manager';\nimport {browser} from '../util/browser';\nimport {Dispatcher} from '../util/dispatcher';\nimport {validateStyle, emitValidationErrors as _emitValidationErrors} from './validate_style';\nimport {Source} from '../source/source';\nimport {QueryRenderedFeaturesOptions, QuerySourceFeatureOptions, queryRenderedFeatures, queryRenderedSymbols, querySourceFeatures} from '../source/query_features';\nimport {SourceCache} from '../source/source_cache';\nimport {GeoJSONSource} from '../source/geojson_source';\nimport {latest as styleSpec, derefLayers as deref, emptyStyle, diff as diffStyles, DiffCommand} from '@maplibre/maplibre-gl-style-spec';\nimport {getGlobalWorkerPool} from '../util/global_worker_pool';\nimport {rtlMainThreadPluginFactory} from '../source/rtl_text_plugin_main_thread';\nimport {RTLPluginLoadedEventName} from '../source/rtl_text_plugin_status';\nimport {PauseablePlacement} from './pauseable_placement';\nimport {ZoomHistory} from './zoom_history';\nimport {CrossTileSymbolIndex} from '../symbol/cross_tile_symbol_index';\nimport {validateCustomStyleLayer} from './style_layer/custom_style_layer';\nimport type {MapGeoJSONFeature} from '../util/vectortile_to_geojson';\n\n// We're skipping validation errors with the `source.canvas` identifier in order\n// to continue to allow canvas sources to be added at runtime/updated in\n// smart setStyle (see https://github.com/mapbox/mapbox-gl-js/pull/6424):\nconst emitValidationErrors = (evented: Evented, errors?: ReadonlyArray<{\n message: string;\n identifier?: string;\n}> | null) =>\n _emitValidationErrors(evented, errors && errors.filter(error => error.identifier !== 'source.canvas'));\n\nimport type {Map} from '../ui/map';\nimport type {Transform} from '../geo/transform';\nimport type {StyleImage} from './style_image';\nimport type {EvaluationParameters} from './evaluation_parameters';\nimport type {Placement} from '../symbol/placement';\nimport type {\n LayerSpecification,\n FilterSpecification,\n StyleSpecification,\n LightSpecification,\n SourceSpecification,\n SpriteSpecification,\n DiffOperations,\n SkySpecification\n} from '@maplibre/maplibre-gl-style-spec';\nimport type {CanvasSourceSpecification} from '../source/canvas_source';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer';\nimport type {Validator} from './validate_style';\nimport {\n MessageType,\n type GetGlyphsParameters,\n type GetGlyphsResponse,\n type GetImagesParameters,\n type GetImagesResponse\n} from '../util/actor_messages';\n\nconst empty = emptyStyle() as StyleSpecification;\n/**\n * A feature identifier that is bound to a source\n */\nexport type FeatureIdentifier = {\n /**\n * Unique id of the feature.\n */\n id?: string | number | undefined;\n /**\n * The id of the vector or GeoJSON source for the feature.\n */\n source: string;\n /**\n * *For vector tile sources, `sourceLayer` is required.*\n */\n sourceLayer?: string | undefined;\n};\n\n/**\n * The options object related to the {@link Map}'s style related methods\n */\nexport type StyleOptions = {\n /**\n * If false, style validation will be skipped. Useful in production environment.\n */\n validate?: boolean;\n /**\n * Defines a CSS\n * font-family for locally overriding generation of Chinese, Japanese, and Korean characters.\n * For these characters, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).\n * Set to `false`, to enable font settings from the map's style for these glyph ranges.\n * Forces a full update.\n */\n localIdeographFontFamily?: string | false;\n};\n\n/**\n * Supporting type to add validation to another style related type\n */\nexport type StyleSetterOptions = {\n /**\n * Whether to check if the filter conforms to the MapLibre Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.\n */\n validate?: boolean;\n};\n\n/**\n * Part of {@link Map#setStyle} options, transformStyle is a convenience function that allows to modify a style after it is fetched but before it is committed to the map state.\n *\n * This function exposes previous and next styles, it can be commonly used to support a range of functionalities like:\n *\n * - when previous style carries certain 'state' that needs to be carried over to a new style gracefully;\n * - when a desired style is a certain combination of previous and incoming style;\n * - when an incoming style requires modification based on external state.\n *\n * @param previous - The current style.\n * @param next - The next style.\n * @returns resulting style that will to be applied to the map\n *\n * @example\n * ```ts\n * map.setStyle('https://demotiles.maplibre.org/style.json', {\n * transformStyle: (previousStyle, nextStyle) => ({\n * ...nextStyle,\n * sources: {\n * ...nextStyle.sources,\n * // copy a source from previous style\n * 'osm': previousStyle.sources.osm\n * },\n * layers: [\n * // background layer\n * nextStyle.layers[0],\n * // copy a layer from previous style\n * previousStyle.layers[0],\n * // other layers from the next style\n * ...nextStyle.layers.slice(1).map(layer => {\n * // hide the layers we don't need from demotiles style\n * if (layer.id.startsWith('geolines')) {\n * layer.layout = {...layer.layout || {}, visibility: 'none'};\n * // filter out US polygons\n * } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) {\n * layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA'];\n * }\n * return layer;\n * })\n * ]\n * })\n * });\n * ```\n */\nexport type TransformStyleFunction = (previous: StyleSpecification | undefined, next: StyleSpecification) => StyleSpecification;\n\n/**\n * The options object related to the {@link Map}'s style related methods\n */\nexport type StyleSwapOptions = {\n /**\n * If false, force a 'full' update, removing the current style\n * and building the given one instead of attempting a diff-based update.\n */\n diff?: boolean;\n /**\n * TransformStyleFunction is a convenience function\n * that allows to modify a style after it is fetched but before it is committed to the map state. Refer to {@link TransformStyleFunction}.\n */\n transformStyle?: TransformStyleFunction;\n}\n\n/**\n * Specifies a layer to be added to a {@link Style}. In addition to a standard {@link LayerSpecification}\n * or a {@link CustomLayerInterface}, a {@link LayerSpecification} with an embedded {@link SourceSpecification} can also be provided.\n */\nexport type AddLayerObject = LayerSpecification | (Omit & {source: SourceSpecification}) | CustomLayerInterface;\n\n/**\n * The Style base class\n */\nexport class Style extends Evented {\n map: Map;\n stylesheet: StyleSpecification;\n dispatcher: Dispatcher;\n imageManager: ImageManager;\n glyphManager: GlyphManager;\n lineAtlas: LineAtlas;\n light: Light;\n sky: Sky;\n\n _frameRequest: AbortController;\n _loadStyleRequest: AbortController;\n _spriteRequest: AbortController;\n _layers: {[_: string]: StyleLayer};\n _serializedLayers: {[_: string]: LayerSpecification};\n _order: Array;\n sourceCaches: {[_: string]: SourceCache};\n zoomHistory: ZoomHistory;\n _loaded: boolean;\n _changed: boolean;\n _updatedSources: {[_: string]: 'clear' | 'reload'};\n _updatedLayers: {[_: string]: true};\n _removedLayers: {[_: string]: StyleLayer};\n _changedImages: {[_: string]: true};\n _glyphsDidChange: boolean;\n _updatedPaintProps: {[layer: string]: true};\n _layerOrderChanged: boolean;\n // image ids of images loaded from style's sprite\n _spritesImagesIds: {[spriteId: string]: string[]};\n // image ids of all images loaded (sprite + user)\n _availableImages: Array;\n\n crossTileSymbolIndex: CrossTileSymbolIndex;\n pauseablePlacement: PauseablePlacement;\n placement: Placement;\n z: number;\n\n constructor(map: Map, options: StyleOptions = {}) {\n super();\n\n this.map = map;\n this.dispatcher = new Dispatcher(getGlobalWorkerPool(), map._getMapId());\n this.dispatcher.registerMessageHandler(MessageType.getGlyphs, (mapId, params) => {\n return this.getGlyphs(mapId, params);\n });\n this.dispatcher.registerMessageHandler(MessageType.getImages, (mapId, params) => {\n return this.getImages(mapId, params);\n });\n this.imageManager = new ImageManager();\n this.imageManager.setEventedParent(this);\n this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily);\n this.lineAtlas = new LineAtlas(256, 512);\n this.crossTileSymbolIndex = new CrossTileSymbolIndex();\n\n this._spritesImagesIds = {};\n this._layers = {};\n\n this._order = [];\n this.sourceCaches = {};\n this.zoomHistory = new ZoomHistory();\n this._loaded = false;\n this._availableImages = [];\n\n this._resetUpdates();\n\n this.dispatcher.broadcast(MessageType.setReferrer, getReferrer());\n rtlMainThreadPluginFactory().on(RTLPluginLoadedEventName, this._rtlPluginLoaded);\n\n this.on('data', (event) => {\n if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') {\n return;\n }\n\n const sourceCache = this.sourceCaches[event.sourceId];\n if (!sourceCache) {\n return;\n }\n\n const source = sourceCache.getSource();\n if (!source || !source.vectorLayerIds) {\n return;\n }\n\n for (const layerId in this._layers) {\n const layer = this._layers[layerId];\n if (layer.source === source.id) {\n this._validateLayer(layer);\n }\n }\n });\n }\n\n _rtlPluginLoaded = () => {\n for (const id in this.sourceCaches) {\n const sourceType = this.sourceCaches[id].getSource().type;\n if (sourceType === 'vector' || sourceType === 'geojson') {\n // Non-vector sources don't have any symbols buckets to reload when the RTL text plugin loads\n // They also load more quickly, so they're more likely to have already displaying tiles\n // that would be unnecessarily booted by the plugin load event\n this.sourceCaches[id].reload(); // Should be a no-op if the plugin loads before any tiles load\n }\n }\n };\n\n loadURL(url: string, options: StyleSwapOptions & StyleSetterOptions = {}, previousStyle?: StyleSpecification) {\n this.fire(new Event('dataloading', {dataType: 'style'}));\n\n options.validate = typeof options.validate === 'boolean' ?\n options.validate : true;\n\n const request = this.map._requestManager.transformRequest(url, ResourceType.Style);\n this._loadStyleRequest = new AbortController();\n const abortController = this._loadStyleRequest;\n getJSON(request, this._loadStyleRequest).then((response) => {\n this._loadStyleRequest = null;\n this._load(response.data, options, previousStyle);\n }).catch((error) => {\n this._loadStyleRequest = null;\n if (error && !abortController.signal.aborted) { // ignore abort\n this.fire(new ErrorEvent(error));\n }\n });\n }\n\n loadJSON(json: StyleSpecification, options: StyleSetterOptions & StyleSwapOptions = {}, previousStyle?: StyleSpecification) {\n this.fire(new Event('dataloading', {dataType: 'style'}));\n\n this._frameRequest = new AbortController();\n browser.frameAsync(this._frameRequest).then(() => {\n this._frameRequest = null;\n options.validate = options.validate !== false;\n this._load(json, options, previousStyle);\n }).catch(() => {}); // ignore abort\n }\n\n loadEmpty() {\n this.fire(new Event('dataloading', {dataType: 'style'}));\n this._load(empty, {validate: false});\n }\n\n _load(json: StyleSpecification, options: StyleSwapOptions & StyleSetterOptions, previousStyle?: StyleSpecification) {\n const nextState = options.transformStyle ? options.transformStyle(previousStyle, json) : json;\n if (options.validate && emitValidationErrors(this, validateStyle(nextState))) {\n return;\n }\n\n this._loaded = true;\n this.stylesheet = nextState;\n\n for (const id in nextState.sources) {\n this.addSource(id, nextState.sources[id], {validate: false});\n }\n\n if (nextState.sprite) {\n this._loadSprite(nextState.sprite);\n } else {\n this.imageManager.setLoaded(true);\n }\n\n this.glyphManager.setURL(nextState.glyphs);\n this._createLayers();\n\n this.light = new Light(this.stylesheet.light);\n this.sky = new Sky(this.stylesheet.sky);\n\n this.map.setTerrain(this.stylesheet.terrain ?? null);\n\n this.fire(new Event('data', {dataType: 'style'}));\n this.fire(new Event('style.load'));\n }\n\n private _createLayers() {\n const dereferencedLayers = deref(this.stylesheet.layers);\n\n // Broadcast layers to workers first, so that expensive style processing (createStyleLayer)\n // can happen in parallel on both main and worker threads.\n this.dispatcher.broadcast(MessageType.setLayers, dereferencedLayers);\n\n this._order = dereferencedLayers.map((layer) => layer.id);\n this._layers = {};\n\n // reset serialization field, to be populated only when needed\n this._serializedLayers = null;\n for (const layer of dereferencedLayers) {\n const styledLayer = createStyleLayer(layer);\n styledLayer.setEventedParent(this, {layer: {id: layer.id}});\n this._layers[layer.id] = styledLayer;\n }\n }\n\n _loadSprite(sprite: SpriteSpecification, isUpdate: boolean = false, completion: (err: Error) => void = undefined) {\n this.imageManager.setLoaded(false);\n\n this._spriteRequest = new AbortController();\n let err: Error;\n loadSprite(sprite, this.map._requestManager, this.map.getPixelRatio(), this._spriteRequest).then((images) => {\n this._spriteRequest = null;\n if (images) {\n for (const spriteId in images) {\n this._spritesImagesIds[spriteId] = [];\n\n // remove old sprite's loaded images (for the same sprite id) that are not in new sprite\n const imagesToRemove = this._spritesImagesIds[spriteId] ? this._spritesImagesIds[spriteId].filter(id => !(id in images)) : [];\n for (const id of imagesToRemove) {\n this.imageManager.removeImage(id);\n this._changedImages[id] = true;\n }\n\n for (const id in images[spriteId]) {\n // don't prefix images of the \"default\" sprite\n const imageId = spriteId === 'default' ? id : `${spriteId}:${id}`;\n // save all the sprite's images' ids to be able to delete them in `removeSprite`\n this._spritesImagesIds[spriteId].push(imageId);\n if (imageId in this.imageManager.images) {\n this.imageManager.updateImage(imageId, images[spriteId][id], false);\n } else {\n this.imageManager.addImage(imageId, images[spriteId][id]);\n }\n\n if (isUpdate) {\n this._changedImages[imageId] = true;\n }\n }\n }\n }\n }).catch((error) => {\n this._spriteRequest = null;\n err = error;\n this.fire(new ErrorEvent(err));\n }).finally(() => {\n this.imageManager.setLoaded(true);\n this._availableImages = this.imageManager.listImages();\n\n if (isUpdate) {\n this._changed = true;\n }\n\n this.dispatcher.broadcast(MessageType.setImages, this._availableImages);\n this.fire(new Event('data', {dataType: 'style'}));\n\n if (completion) {\n completion(err);\n }\n });\n }\n\n _unloadSprite() {\n for (const id of Object.values(this._spritesImagesIds).flat()) {\n this.imageManager.removeImage(id);\n this._changedImages[id] = true;\n }\n\n this._spritesImagesIds = {};\n this._availableImages = this.imageManager.listImages();\n this._changed = true;\n this.dispatcher.broadcast(MessageType.setImages, this._availableImages);\n this.fire(new Event('data', {dataType: 'style'}));\n }\n\n _validateLayer(layer: StyleLayer) {\n const sourceCache = this.sourceCaches[layer.source];\n if (!sourceCache) {\n return;\n }\n\n const sourceLayer = layer.sourceLayer;\n if (!sourceLayer) {\n return;\n }\n\n const source = sourceCache.getSource();\n if (source.type === 'geojson' || (source.vectorLayerIds && source.vectorLayerIds.indexOf(sourceLayer) === -1)) {\n this.fire(new ErrorEvent(new Error(\n `Source layer \"${sourceLayer}\" ` +\n `does not exist on source \"${source.id}\" ` +\n `as specified by style layer \"${layer.id}\".`\n )));\n }\n }\n\n loaded() {\n if (!this._loaded)\n return false;\n\n if (Object.keys(this._updatedSources).length)\n return false;\n\n for (const id in this.sourceCaches)\n if (!this.sourceCaches[id].loaded())\n return false;\n\n if (!this.imageManager.isLoaded())\n return false;\n\n return true;\n }\n\n /**\n * @hidden\n * take an array of string IDs, and based on this._layers, generate an array of LayerSpecification\n * @param ids - an array of string IDs, for which serialized layers will be generated. If omitted, all serialized layers will be returned\n * @param returnClose - if true, return a clone of the layer object\n * @returns generated result\n */\n private _serializeByIds(ids: Array, returnClone: boolean = false): Array {\n\n const serializedLayersDictionary = this._serializedAllLayers();\n if (!ids || ids.length === 0) {\n return returnClone ? Object.values(clone(serializedLayersDictionary)) : Object.values(serializedLayersDictionary);\n }\n\n const serializedLayers = [];\n for (const id of ids) {\n // this check will skip all custom layers\n if (serializedLayersDictionary[id]) {\n const toPush = returnClone ? clone(serializedLayersDictionary[id]) : serializedLayersDictionary[id];\n serializedLayers.push(toPush);\n }\n }\n\n return serializedLayers;\n }\n\n /**\n * @hidden\n * Lazy initialization of this._serializedLayers dictionary and return it\n * @returns this._serializedLayers dictionary\n */\n private _serializedAllLayers(): {[_: string]: LayerSpecification} {\n let serializedLayers = this._serializedLayers;\n if (serializedLayers) {\n return serializedLayers;\n }\n\n serializedLayers = this._serializedLayers = {};\n const allLayerIds: string [] = Object.keys(this._layers);\n for (const layerId of allLayerIds) {\n const layer = this._layers[layerId];\n if (layer.type !== 'custom') {\n serializedLayers[layerId] = layer.serialize();\n }\n }\n\n return serializedLayers;\n }\n\n hasTransitions() {\n if (this.light && this.light.hasTransition()) {\n return true;\n }\n\n if (this.sky && this.sky.hasTransition()) {\n return true;\n }\n\n for (const id in this.sourceCaches) {\n if (this.sourceCaches[id].hasTransition()) {\n return true;\n }\n }\n\n for (const id in this._layers) {\n if (this._layers[id].hasTransition()) {\n return true;\n }\n }\n\n return false;\n }\n\n _checkLoaded() {\n if (!this._loaded) {\n throw new Error('Style is not done loading.');\n }\n }\n\n /**\n * @internal\n * Apply queued style updates in a batch and recalculate zoom-dependent paint properties.\n */\n update(parameters: EvaluationParameters) {\n if (!this._loaded) {\n return;\n }\n\n const changed = this._changed;\n if (changed) {\n const updatedIds = Object.keys(this._updatedLayers);\n const removedIds = Object.keys(this._removedLayers);\n\n if (updatedIds.length || removedIds.length) {\n this._updateWorkerLayers(updatedIds, removedIds);\n }\n for (const id in this._updatedSources) {\n const action = this._updatedSources[id];\n\n if (action === 'reload') {\n this._reloadSource(id);\n } else if (action === 'clear') {\n this._clearSource(id);\n } else {\n throw new Error(`Invalid action ${action}`);\n }\n }\n\n this._updateTilesForChangedImages();\n this._updateTilesForChangedGlyphs();\n\n for (const id in this._updatedPaintProps) {\n this._layers[id].updateTransitions(parameters);\n }\n\n this.light.updateTransitions(parameters);\n this.sky.updateTransitions(parameters);\n\n this._resetUpdates();\n }\n\n const sourcesUsedBefore = {};\n\n // save 'used' status to sourcesUsedBefore object and reset all sourceCaches 'used' field to false\n for (const sourceCacheId in this.sourceCaches) {\n const sourceCache = this.sourceCaches[sourceCacheId];\n\n // sourceCache.used could be undefined, and sourcesUsedBefore[sourceCacheId] is also 'undefined'\n sourcesUsedBefore[sourceCacheId] = sourceCache.used;\n sourceCache.used = false;\n }\n\n // loop all layers and find layers that are not hidden at parameters.zoom\n // and set used to true in sourceCaches dictionary for the sources of these layers\n for (const layerId of this._order) {\n const layer = this._layers[layerId];\n\n layer.recalculate(parameters, this._availableImages);\n if (!layer.isHidden(parameters.zoom) && layer.source) {\n this.sourceCaches[layer.source].used = true;\n }\n }\n\n // cross check sourcesUsedBefore against updated this.sourceCaches dictionary\n // if \"used\" field is different fire visibility event\n for (const sourcesUsedBeforeId in sourcesUsedBefore) {\n const sourceCache = this.sourceCaches[sourcesUsedBeforeId];\n\n // (undefine !== false) will evaluate to true and fire an useless visibility event\n // need force \"falsy\" values to boolean to avoid the case above\n if (!!sourcesUsedBefore[sourcesUsedBeforeId] !== !!sourceCache.used) {\n sourceCache.fire(new Event('data',\n {\n sourceDataType: 'visibility',\n dataType: 'source',\n sourceId: sourcesUsedBeforeId\n }));\n }\n }\n\n this.light.recalculate(parameters);\n this.sky.recalculate(parameters);\n this.z = parameters.zoom;\n\n if (changed) {\n this.fire(new Event('data', {dataType: 'style'}));\n }\n }\n\n /*\n * Apply any queued image changes.\n */\n _updateTilesForChangedImages() {\n const changedImages = Object.keys(this._changedImages);\n if (changedImages.length) {\n for (const name in this.sourceCaches) {\n this.sourceCaches[name].reloadTilesForDependencies(['icons', 'patterns'], changedImages);\n }\n this._changedImages = {};\n }\n }\n\n _updateTilesForChangedGlyphs() {\n if (this._glyphsDidChange) {\n for (const name in this.sourceCaches) {\n this.sourceCaches[name].reloadTilesForDependencies(['glyphs'], ['']);\n }\n this._glyphsDidChange = false;\n }\n }\n\n _updateWorkerLayers(updatedIds: Array, removedIds: Array) {\n this.dispatcher.broadcast(MessageType.updateLayers, {\n layers: this._serializeByIds(updatedIds, false),\n removedIds\n });\n }\n\n _resetUpdates() {\n this._changed = false;\n\n this._updatedLayers = {};\n this._removedLayers = {};\n\n this._updatedSources = {};\n this._updatedPaintProps = {};\n\n this._changedImages = {};\n this._glyphsDidChange = false;\n }\n\n /**\n * Update this style's state to match the given style JSON, performing only\n * the necessary mutations.\n *\n * May throw an Error ('Unimplemented: METHOD') if the mapbox-gl-style-spec\n * diff algorithm produces an operation that is not supported.\n *\n * @returns true if any changes were made; false otherwise\n */\n setState(nextState: StyleSpecification, options: StyleSwapOptions & StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const serializedStyle = this.serialize();\n nextState = options.transformStyle ? options.transformStyle(serializedStyle, nextState) : nextState;\n const validate = options.validate ?? true;\n if (validate && emitValidationErrors(this, validateStyle(nextState))) return false;\n\n nextState = clone(nextState);\n nextState.layers = deref(nextState.layers);\n\n const changes = diffStyles(serializedStyle, nextState);\n const operations = this._getOperationsToPerform(changes);\n\n if (operations.unimplemented.length > 0) {\n throw new Error(`Unimplemented: ${operations.unimplemented.join(', ')}.`);\n }\n\n if (operations.operations.length === 0) {\n return false;\n }\n\n for (const styleChangeOperation of operations.operations) {\n styleChangeOperation();\n }\n\n this.stylesheet = nextState;\n\n // reset serialization field, to be populated only when needed\n this._serializedLayers = null;\n\n return true;\n }\n\n _getOperationsToPerform(diff: DiffCommand[]) {\n const operations: Function[] = [];\n const unimplemented: string[] = [];\n for (const op of diff) {\n switch (op.command) {\n case 'setCenter':\n case 'setZoom':\n case 'setBearing':\n case 'setPitch':\n continue;\n case 'addLayer':\n operations.push(() => this.addLayer.apply(this, op.args));\n break;\n case 'removeLayer':\n operations.push(() => this.removeLayer.apply(this, op.args));\n break;\n case 'setPaintProperty':\n operations.push(() => this.setPaintProperty.apply(this, op.args));\n break;\n case 'setLayoutProperty':\n operations.push(() => this.setLayoutProperty.apply(this, op.args));\n break;\n case 'setFilter':\n operations.push(() => this.setFilter.apply(this, op.args));\n break;\n case 'addSource':\n operations.push(() => this.addSource.apply(this, op.args));\n break;\n case 'removeSource':\n operations.push(() => this.removeSource.apply(this, op.args));\n break;\n case 'setLayerZoomRange':\n operations.push(() => this.setLayerZoomRange.apply(this, op.args));\n break;\n case 'setLight':\n operations.push(() => this.setLight.apply(this, op.args));\n break;\n case 'setGeoJSONSourceData':\n operations.push(() => this.setGeoJSONSourceData.apply(this, op.args));\n break;\n case 'setGlyphs':\n operations.push(() => this.setGlyphs.apply(this, op.args));\n break;\n case 'setSprite':\n operations.push(() => this.setSprite.apply(this, op.args));\n break;\n case 'setSky':\n operations.push(() => this.setSky.apply(this, op.args));\n break;\n case 'setTerrain':\n operations.push(() => this.map.setTerrain.apply(this, op.args));\n break;\n case 'setTransition':\n operations.push(() => {});\n break;\n default:\n unimplemented.push(op.command);\n break;\n }\n }\n return {\n operations,\n unimplemented\n };\n }\n\n addImage(id: string, image: StyleImage) {\n if (this.getImage(id)) {\n return this.fire(new ErrorEvent(new Error(`An image named \"${id}\" already exists.`)));\n }\n this.imageManager.addImage(id, image);\n this._afterImageUpdated(id);\n }\n\n updateImage(id: string, image: StyleImage) {\n this.imageManager.updateImage(id, image);\n }\n\n getImage(id: string): StyleImage {\n return this.imageManager.getImage(id);\n }\n\n removeImage(id: string) {\n if (!this.getImage(id)) {\n return this.fire(new ErrorEvent(new Error(`An image named \"${id}\" does not exist.`)));\n }\n this.imageManager.removeImage(id);\n this._afterImageUpdated(id);\n }\n\n _afterImageUpdated(id: string) {\n this._availableImages = this.imageManager.listImages();\n this._changedImages[id] = true;\n this._changed = true;\n this.dispatcher.broadcast(MessageType.setImages, this._availableImages);\n this.fire(new Event('data', {dataType: 'style'}));\n }\n\n listImages() {\n this._checkLoaded();\n\n return this.imageManager.listImages();\n }\n\n addSource(id: string, source: SourceSpecification | CanvasSourceSpecification, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n if (this.sourceCaches[id] !== undefined) {\n throw new Error(`Source \"${id}\" already exists.`);\n }\n\n if (!source.type) {\n throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(', ')}.`);\n }\n\n const builtIns = ['vector', 'raster', 'geojson', 'video', 'image'];\n const shouldValidate = builtIns.indexOf(source.type) >= 0;\n if (shouldValidate && this._validate(validateStyle.source, `sources.${id}`, source, null, options)) return;\n if (this.map && this.map._collectResourceTiming) (source as any).collectResourceTiming = true;\n const sourceCache = this.sourceCaches[id] = new SourceCache(id, source, this.dispatcher);\n sourceCache.style = this;\n sourceCache.setEventedParent(this, () => ({\n isSourceLoaded: sourceCache.loaded(),\n source: sourceCache.serialize(),\n sourceId: id\n }));\n\n sourceCache.onAdd(this.map);\n this._changed = true;\n }\n\n /**\n * Remove a source from this stylesheet, given its id.\n * @param id - id of the source to remove\n * @throws if no source is found with the given ID\n */\n removeSource(id: string): this {\n this._checkLoaded();\n\n if (this.sourceCaches[id] === undefined) {\n throw new Error('There is no source with this ID');\n }\n for (const layerId in this._layers) {\n if (this._layers[layerId].source === id) {\n return this.fire(new ErrorEvent(new Error(`Source \"${id}\" cannot be removed while layer \"${layerId}\" is using it.`)));\n }\n }\n\n const sourceCache = this.sourceCaches[id];\n delete this.sourceCaches[id];\n delete this._updatedSources[id];\n sourceCache.fire(new Event('data', {sourceDataType: 'metadata', dataType: 'source', sourceId: id}));\n sourceCache.setEventedParent(null);\n sourceCache.onRemove(this.map);\n this._changed = true;\n }\n\n /**\n * Set the data of a GeoJSON source, given its id.\n * @param id - id of the source\n * @param data - GeoJSON source\n */\n setGeoJSONSourceData(id: string, data: GeoJSON.GeoJSON | string) {\n this._checkLoaded();\n\n if (this.sourceCaches[id] === undefined) throw new Error(`There is no source with this ID=${id}`);\n const geojsonSource: GeoJSONSource = (this.sourceCaches[id].getSource() as any);\n if (geojsonSource.type !== 'geojson') throw new Error(`geojsonSource.type is ${geojsonSource.type}, which is !== 'geojson`);\n\n geojsonSource.setData(data);\n this._changed = true;\n }\n\n /**\n * Get a source by ID.\n * @param id - ID of the desired source\n * @returns source\n */\n getSource(id: string): Source | undefined {\n return this.sourceCaches[id] && this.sourceCaches[id].getSource();\n }\n\n /**\n * Add a layer to the map style. The layer will be inserted before the layer with\n * ID `before`, or appended if `before` is omitted.\n * @param layerObject - The style layer to add.\n * @param before - ID of an existing layer to insert before\n * @param options - Style setter options.\n */\n addLayer(layerObject: AddLayerObject, before?: string, options: StyleSetterOptions = {}): this {\n this._checkLoaded();\n\n const id = layerObject.id;\n\n if (this.getLayer(id)) {\n this.fire(new ErrorEvent(new Error(`Layer \"${id}\" already exists on this map.`)));\n return;\n }\n\n let layer: ReturnType;\n if (layerObject.type === 'custom') {\n\n if (emitValidationErrors(this, validateCustomStyleLayer(layerObject))) return;\n\n layer = createStyleLayer(layerObject);\n\n } else {\n if ('source' in layerObject && typeof layerObject.source === 'object') {\n this.addSource(id, layerObject.source);\n layerObject = clone(layerObject);\n layerObject = extend(layerObject, {source: id});\n }\n\n // this layer is not in the style.layers array, so we pass an impossible array index\n if (this._validate(validateStyle.layer,\n `layers.${id}`, layerObject, {arrayIndex: -1}, options)) return;\n\n layer = createStyleLayer(layerObject as LayerSpecification | CustomLayerInterface);\n this._validateLayer(layer);\n\n layer.setEventedParent(this, {layer: {id}});\n }\n\n const index = before ? this._order.indexOf(before) : this._order.length;\n if (before && index === -1) {\n this.fire(new ErrorEvent(new Error(`Cannot add layer \"${id}\" before non-existing layer \"${before}\".`)));\n return;\n }\n\n this._order.splice(index, 0, id);\n this._layerOrderChanged = true;\n\n this._layers[id] = layer;\n\n if (this._removedLayers[id] && layer.source && layer.type !== 'custom') {\n // If, in the current batch, we have already removed this layer\n // and we are now re-adding it with a different `type`, then we\n // need to clear (rather than just reload) the underlying source's\n // tiles. Otherwise, tiles marked 'reloading' will have buckets /\n // buffers that are set up for the _previous_ version of this\n // layer, causing, e.g.:\n // https://github.com/mapbox/mapbox-gl-js/issues/3633\n const removed = this._removedLayers[id];\n delete this._removedLayers[id];\n if (removed.type !== layer.type) {\n this._updatedSources[layer.source] = 'clear';\n } else {\n this._updatedSources[layer.source] = 'reload';\n this.sourceCaches[layer.source].pause();\n }\n }\n this._updateLayer(layer);\n\n if (layer.onAdd) {\n layer.onAdd(this.map);\n }\n }\n\n /**\n * Moves a layer to a different z-position. The layer will be inserted before the layer with\n * ID `before`, or appended if `before` is omitted.\n * @param id - ID of the layer to move\n * @param before - ID of an existing layer to insert before\n */\n moveLayer(id: string, before?: string) {\n this._checkLoaded();\n this._changed = true;\n\n const layer = this._layers[id];\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`)));\n return;\n }\n\n if (id === before) {\n return;\n }\n\n const index = this._order.indexOf(id);\n this._order.splice(index, 1);\n\n const newIndex = before ? this._order.indexOf(before) : this._order.length;\n if (before && newIndex === -1) {\n this.fire(new ErrorEvent(new Error(`Cannot move layer \"${id}\" before non-existing layer \"${before}\".`)));\n return;\n }\n this._order.splice(newIndex, 0, id);\n\n this._layerOrderChanged = true;\n }\n\n /**\n * Remove the layer with the given id from the style.\n * A {@link ErrorEvent} event will be fired if no such layer exists.\n *\n * @param id - id of the layer to remove\n */\n removeLayer(id: string) {\n this._checkLoaded();\n\n const layer = this._layers[id];\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`Cannot remove non-existing layer \"${id}\".`)));\n return;\n }\n\n layer.setEventedParent(null);\n\n const index = this._order.indexOf(id);\n this._order.splice(index, 1);\n\n this._layerOrderChanged = true;\n this._changed = true;\n this._removedLayers[id] = layer;\n delete this._layers[id];\n\n if (this._serializedLayers) {\n delete this._serializedLayers[id];\n }\n delete this._updatedLayers[id];\n delete this._updatedPaintProps[id];\n\n if (layer.onRemove) {\n layer.onRemove(this.map);\n }\n }\n\n /**\n * Return the style layer object with the given `id`.\n *\n * @param id - id of the desired layer\n * @returns a layer, if one with the given `id` exists\n */\n getLayer(id: string): StyleLayer | undefined {\n return this._layers[id];\n }\n\n /**\n * Return the ids of all layers currently in the style, including custom layers, in order.\n *\n * @returns ids of layers, in order\n */\n getLayersOrder(): string[] {\n return [...this._order];\n }\n\n /**\n * Checks if a specific layer is present within the style.\n *\n * @param id - the id of the desired layer\n * @returns a boolean specifying if the given layer is present\n */\n hasLayer(id: string): boolean {\n return id in this._layers;\n }\n\n setLayerZoomRange(layerId: string, minzoom?: number | null, maxzoom?: number | null) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`Cannot set the zoom range of non-existing layer \"${layerId}\".`)));\n return;\n }\n\n if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) return;\n\n if (minzoom != null) {\n layer.minzoom = minzoom;\n }\n if (maxzoom != null) {\n layer.maxzoom = maxzoom;\n }\n this._updateLayer(layer);\n }\n\n setFilter(layerId: string, filter?: FilterSpecification | null, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`Cannot filter non-existing layer \"${layerId}\".`)));\n return;\n }\n\n if (deepEqual(layer.filter, filter)) {\n return;\n }\n\n if (filter === null || filter === undefined) {\n layer.filter = undefined;\n this._updateLayer(layer);\n return;\n }\n\n if (this._validate(validateStyle.filter, `layers.${layer.id}.filter`, filter, null, options)) {\n return;\n }\n\n layer.filter = clone(filter);\n this._updateLayer(layer);\n }\n\n /**\n * Get a layer's filter object\n * @param layer - the layer to inspect\n * @returns the layer's filter, if any\n */\n getFilter(layer: string): FilterSpecification | void {\n return clone(this.getLayer(layer).filter);\n }\n\n setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`Cannot style non-existing layer \"${layerId}\".`)));\n return;\n }\n\n if (deepEqual(layer.getLayoutProperty(name), value)) return;\n\n layer.setLayoutProperty(name, value, options);\n this._updateLayer(layer);\n }\n\n /**\n * Get a layout property's value from a given layer\n * @param layerId - the layer to inspect\n * @param name - the name of the layout property\n * @returns the property value\n */\n getLayoutProperty(layerId: string, name: string) {\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`Cannot get style of non-existing layer \"${layerId}\".`)));\n return;\n }\n\n return layer.getLayoutProperty(name);\n }\n\n setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`Cannot style non-existing layer \"${layerId}\".`)));\n return;\n }\n\n if (deepEqual(layer.getPaintProperty(name), value)) return;\n\n const requiresRelayout = layer.setPaintProperty(name, value, options);\n if (requiresRelayout) {\n this._updateLayer(layer);\n }\n\n this._changed = true;\n this._updatedPaintProps[layerId] = true;\n // reset serialization field, to be populated only when needed\n this._serializedLayers = null;\n }\n\n getPaintProperty(layer: string, name: string) {\n return this.getLayer(layer).getPaintProperty(name);\n }\n\n setFeatureState(target: FeatureIdentifier, state: any) {\n this._checkLoaded();\n const sourceId = target.source;\n const sourceLayer = target.sourceLayer;\n const sourceCache = this.sourceCaches[sourceId];\n\n if (sourceCache === undefined) {\n this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));\n return;\n }\n const sourceType = sourceCache.getSource().type;\n if (sourceType === 'geojson' && sourceLayer) {\n this.fire(new ErrorEvent(new Error('GeoJSON sources cannot have a sourceLayer parameter.')));\n return;\n }\n if (sourceType === 'vector' && !sourceLayer) {\n this.fire(new ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.')));\n return;\n }\n if (target.id === undefined) {\n this.fire(new ErrorEvent(new Error('The feature id parameter must be provided.')));\n }\n\n sourceCache.setFeatureState(sourceLayer, target.id, state);\n }\n\n removeFeatureState(target: FeatureIdentifier, key?: string) {\n this._checkLoaded();\n const sourceId = target.source;\n const sourceCache = this.sourceCaches[sourceId];\n\n if (sourceCache === undefined) {\n this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));\n return;\n }\n\n const sourceType = sourceCache.getSource().type;\n const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined;\n\n if (sourceType === 'vector' && !sourceLayer) {\n this.fire(new ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.')));\n return;\n }\n\n if (key && (typeof target.id !== 'string' && typeof target.id !== 'number')) {\n this.fire(new ErrorEvent(new Error('A feature id is required to remove its specific state property.')));\n return;\n }\n\n sourceCache.removeFeatureState(sourceLayer, target.id, key);\n }\n\n getFeatureState(target: FeatureIdentifier) {\n this._checkLoaded();\n const sourceId = target.source;\n const sourceLayer = target.sourceLayer;\n const sourceCache = this.sourceCaches[sourceId];\n\n if (sourceCache === undefined) {\n this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));\n return;\n }\n const sourceType = sourceCache.getSource().type;\n if (sourceType === 'vector' && !sourceLayer) {\n this.fire(new ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.')));\n return;\n }\n if (target.id === undefined) {\n this.fire(new ErrorEvent(new Error('The feature id parameter must be provided.')));\n }\n\n return sourceCache.getFeatureState(sourceLayer, target.id);\n }\n\n getTransition() {\n return extend({duration: 300, delay: 0}, this.stylesheet && this.stylesheet.transition);\n }\n\n serialize(): StyleSpecification | undefined {\n // We return undefined before we're loaded, following the pattern of Map.getStyle() before\n // the Style object is initialized.\n // Internally, Style._validate() calls Style.serialize() but callers are responsible for\n // calling Style._checkLoaded() first if their validation requires the style to be loaded.\n if (!this._loaded) return;\n\n const sources = mapObject(this.sourceCaches, (source) => source.serialize());\n const layers = this._serializeByIds(this._order, true);\n const terrain = this.map.getTerrain() || undefined;\n const myStyleSheet = this.stylesheet;\n\n return filterObject({\n version: myStyleSheet.version,\n name: myStyleSheet.name,\n metadata: myStyleSheet.metadata,\n light: myStyleSheet.light,\n sky: myStyleSheet.sky,\n center: myStyleSheet.center,\n zoom: myStyleSheet.zoom,\n bearing: myStyleSheet.bearing,\n pitch: myStyleSheet.pitch,\n sprite: myStyleSheet.sprite,\n glyphs: myStyleSheet.glyphs,\n transition: myStyleSheet.transition,\n sources,\n layers,\n terrain\n },\n (value) => { return value !== undefined; });\n }\n\n _updateLayer(layer: StyleLayer) {\n this._updatedLayers[layer.id] = true;\n if (layer.source && !this._updatedSources[layer.source] &&\n //Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865)\n this.sourceCaches[layer.source].getSource().type !== 'raster') {\n this._updatedSources[layer.source] = 'reload';\n this.sourceCaches[layer.source].pause();\n }\n\n // upon updating, serialized layer dictionary should be reset.\n // When needed, it will be populated with the correct copy again.\n this._serializedLayers = null;\n this._changed = true;\n }\n\n _flattenAndSortRenderedFeatures(sourceResults: Array<{ [key: string]: Array<{featureIndex: number; feature: MapGeoJSONFeature}> }>) {\n // Feature order is complicated.\n // The order between features in two 2D layers is always determined by layer order.\n // The order between features in two 3D layers is always determined by depth.\n // The order between a feature in a 2D layer and a 3D layer is tricky:\n // Most often layer order determines the feature order in this case. If\n // a line layer is above a extrusion layer the line feature will be rendered\n // above the extrusion. If the line layer is below the extrusion layer,\n // it will be rendered below it.\n //\n // There is a weird case though.\n // You have layers in this order: extrusion_layer_a, line_layer, extrusion_layer_b\n // Each layer has a feature that overlaps the other features.\n // The feature in extrusion_layer_a is closer than the feature in extrusion_layer_b so it is rendered above.\n // The feature in line_layer is rendered above extrusion_layer_a.\n // This means that that the line_layer feature is above the extrusion_layer_b feature despite\n // it being in an earlier layer.\n\n const isLayer3D = layerId => this._layers[layerId].type === 'fill-extrusion';\n\n const layerIndex = {};\n const features3D = [];\n for (let l = this._order.length - 1; l >= 0; l--) {\n const layerId = this._order[l];\n if (isLayer3D(layerId)) {\n layerIndex[layerId] = l;\n for (const sourceResult of sourceResults) {\n const layerFeatures = sourceResult[layerId];\n if (layerFeatures) {\n for (const featureWrapper of layerFeatures) {\n features3D.push(featureWrapper);\n }\n }\n }\n }\n }\n\n features3D.sort((a, b) => {\n return b.intersectionZ - a.intersectionZ;\n });\n\n const features = [];\n for (let l = this._order.length - 1; l >= 0; l--) {\n const layerId = this._order[l];\n\n if (isLayer3D(layerId)) {\n // add all 3D features that are in or above the current layer\n for (let i = features3D.length - 1; i >= 0; i--) {\n const topmost3D = features3D[i].feature;\n if (layerIndex[topmost3D.layer.id] < l) break;\n features.push(topmost3D);\n features3D.pop();\n }\n } else {\n for (const sourceResult of sourceResults) {\n const layerFeatures = sourceResult[layerId];\n if (layerFeatures) {\n for (const featureWrapper of layerFeatures) {\n features.push(featureWrapper.feature);\n }\n }\n }\n }\n }\n\n return features;\n }\n\n queryRenderedFeatures(queryGeometry: any, params: QueryRenderedFeaturesOptions, transform: Transform) {\n if (params && params.filter) {\n this._validate(validateStyle.filter, 'queryRenderedFeatures.filter', params.filter, null, params);\n }\n\n const includedSources = {};\n if (params && params.layers) {\n if (!Array.isArray(params.layers)) {\n this.fire(new ErrorEvent(new Error('parameters.layers must be an Array.')));\n return [];\n }\n for (const layerId of params.layers) {\n const layer = this._layers[layerId];\n if (!layer) {\n // this layer is not in the style.layers array\n this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be queried for features.`)));\n return [];\n }\n includedSources[layer.source] = true;\n }\n }\n\n const sourceResults = [];\n\n params.availableImages = this._availableImages;\n\n // LayerSpecification is serialized StyleLayer, and this casting is safe.\n const serializedLayers = this._serializedAllLayers() as {[_: string]: StyleLayer};\n\n for (const id in this.sourceCaches) {\n if (params.layers && !includedSources[id]) continue;\n sourceResults.push(\n queryRenderedFeatures(\n this.sourceCaches[id],\n this._layers,\n serializedLayers,\n queryGeometry,\n params,\n transform)\n );\n }\n\n if (this.placement) {\n // If a placement has run, query against its CollisionIndex\n // for symbol results, and treat it as an extra source to merge\n sourceResults.push(\n queryRenderedSymbols(\n this._layers,\n serializedLayers,\n this.sourceCaches,\n queryGeometry,\n params,\n this.placement.collisionIndex,\n this.placement.retainedQueryData)\n );\n }\n\n return this._flattenAndSortRenderedFeatures(sourceResults);\n }\n\n querySourceFeatures(\n sourceID: string,\n params?: QuerySourceFeatureOptions\n ) {\n if (params && params.filter) {\n this._validate(validateStyle.filter, 'querySourceFeatures.filter', params.filter, null, params);\n }\n const sourceCache = this.sourceCaches[sourceID];\n return sourceCache ? querySourceFeatures(sourceCache, params) : [];\n }\n\n getLight() {\n return this.light.getLight();\n }\n\n setLight(lightOptions: LightSpecification, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const light = this.light.getLight();\n let _update = false;\n for (const key in lightOptions) {\n if (!deepEqual(lightOptions[key], light[key])) {\n _update = true;\n break;\n }\n }\n if (!_update) return;\n\n const parameters = {\n now: browser.now(),\n transition: extend({\n duration: 300,\n delay: 0\n }, this.stylesheet.transition)\n };\n\n this.light.setLight(lightOptions, options);\n this.light.updateTransitions(parameters);\n }\n\n getSky(): SkySpecification {\n return this.stylesheet?.sky;\n }\n\n setSky(skyOptions?: SkySpecification, options: StyleSetterOptions = {}) {\n const sky = this.getSky();\n let update = false;\n if (!skyOptions && !sky) return;\n\n if (skyOptions && !sky) {\n update = true;\n } else if (!skyOptions && sky) {\n update = true;\n } else {\n for (const key in skyOptions) {\n if (!deepEqual(skyOptions[key], sky[key])) {\n update = true;\n break;\n }\n }\n }\n if (!update) return;\n\n const parameters = {\n now: browser.now(),\n transition: extend({\n duration: 300,\n delay: 0\n }, this.stylesheet.transition)\n };\n\n this.stylesheet.sky = skyOptions;\n this.sky.setSky(skyOptions, options);\n this.sky.updateTransitions(parameters);\n }\n\n _validate(validate: Validator, key: string, value: any, props: any, options: {\n validate?: boolean;\n } = {}) {\n if (options && options.validate === false) {\n return false;\n }\n return emitValidationErrors(this, validate.call(validateStyle, extend({\n key,\n style: this.serialize(),\n value,\n styleSpec\n }, props)));\n }\n\n _remove(mapRemoved: boolean = true) {\n if (this._frameRequest) {\n this._frameRequest.abort();\n this._frameRequest = null;\n }\n if (this._loadStyleRequest) {\n this._loadStyleRequest.abort();\n this._loadStyleRequest = null;\n }\n if (this._spriteRequest) {\n this._spriteRequest.abort();\n this._spriteRequest = null;\n }\n rtlMainThreadPluginFactory().off(RTLPluginLoadedEventName, this._rtlPluginLoaded);\n for (const layerId in this._layers) {\n const layer: StyleLayer = this._layers[layerId];\n layer.setEventedParent(null);\n }\n for (const id in this.sourceCaches) {\n const sourceCache = this.sourceCaches[id];\n sourceCache.setEventedParent(null);\n sourceCache.onRemove(this.map);\n }\n this.imageManager.setEventedParent(null);\n this.setEventedParent(null);\n if (mapRemoved) {\n this.dispatcher.broadcast(MessageType.removeMap, undefined);\n }\n this.dispatcher.remove(mapRemoved);\n }\n\n _clearSource(id: string) {\n this.sourceCaches[id].clearTiles();\n }\n\n _reloadSource(id: string) {\n this.sourceCaches[id].resume();\n this.sourceCaches[id].reload();\n }\n\n _updateSources(transform: Transform) {\n for (const id in this.sourceCaches) {\n this.sourceCaches[id].update(transform, this.map.terrain);\n }\n }\n\n _generateCollisionBoxes() {\n for (const id in this.sourceCaches) {\n this._reloadSource(id);\n }\n }\n\n _updatePlacement(transform: Transform, showCollisionBoxes: boolean, fadeDuration: number, crossSourceCollisions: boolean, forceFullPlacement: boolean = false) {\n let symbolBucketsChanged = false;\n let placementCommitted = false;\n\n const layerTiles = {};\n\n for (const layerID of this._order) {\n const styleLayer = this._layers[layerID];\n if (styleLayer.type !== 'symbol') continue;\n\n if (!layerTiles[styleLayer.source]) {\n const sourceCache = this.sourceCaches[styleLayer.source];\n layerTiles[styleLayer.source] = sourceCache.getRenderableIds(true)\n .map((id) => sourceCache.getTileByID(id))\n .sort((a, b) => (b.tileID.overscaledZ - a.tileID.overscaledZ) || (a.tileID.isLessThan(b.tileID) ? -1 : 1));\n }\n\n const layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, layerTiles[styleLayer.source], transform.center.lng);\n symbolBucketsChanged = symbolBucketsChanged || layerBucketsChanged;\n }\n this.crossTileSymbolIndex.pruneUnusedLayers(this._order);\n\n // Anything that changes our \"in progress\" layer and tile indices requires us\n // to start over. When we start over, we do a full placement instead of incremental\n // to prevent starvation.\n // We need to restart placement to keep layer indices in sync.\n // Also force full placement when fadeDuration === 0 to ensure that newly loaded\n // tiles will fully display symbols in their first frame\n forceFullPlacement = forceFullPlacement || this._layerOrderChanged || fadeDuration === 0;\n\n if (forceFullPlacement || !this.pauseablePlacement || (this.pauseablePlacement.isDone() && !this.placement.stillRecent(browser.now(), transform.zoom))) {\n this.pauseablePlacement = new PauseablePlacement(transform, this.map.terrain, this._order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement);\n this._layerOrderChanged = false;\n }\n\n if (this.pauseablePlacement.isDone()) {\n // the last placement finished running, but the next one hasn’t\n // started yet because of the `stillRecent` check immediately\n // above, so mark it stale to ensure that we request another\n // render frame\n this.placement.setStale();\n } else {\n this.pauseablePlacement.continuePlacement(this._order, this._layers, layerTiles);\n\n if (this.pauseablePlacement.isDone()) {\n this.placement = this.pauseablePlacement.commit(browser.now());\n placementCommitted = true;\n }\n\n if (symbolBucketsChanged) {\n // since the placement gets split over multiple frames it is possible\n // these buckets were processed before they were changed and so the\n // placement is already stale while it is in progress\n this.pauseablePlacement.placement.setStale();\n }\n }\n\n if (placementCommitted || symbolBucketsChanged) {\n for (const layerID of this._order) {\n const styleLayer = this._layers[layerID];\n if (styleLayer.type !== 'symbol') continue;\n this.placement.updateLayerOpacities(styleLayer, layerTiles[styleLayer.source]);\n }\n }\n\n // needsRender is false when we have just finished a placement that didn't change the visibility of any symbols\n const needsRerender = !this.pauseablePlacement.isDone() || this.placement.hasTransitions(browser.now());\n return needsRerender;\n }\n\n _releaseSymbolFadeTiles() {\n for (const id in this.sourceCaches) {\n this.sourceCaches[id].releaseSymbolFadeTiles();\n }\n }\n\n // Callbacks from web workers\n\n async getImages(mapId: string | number, params: GetImagesParameters): Promise {\n const images = await this.imageManager.getImages(params.icons);\n\n // Apply queued image changes before setting the tile's dependencies so that the tile\n // is not reloaded unnecessarily. Without this forced update the reload could happen in cases\n // like this one:\n // - icons contains \"my-image\"\n // - imageManager.getImages(...) triggers `onstyleimagemissing`\n // - the user adds \"my-image\" within the callback\n // - addImage adds \"my-image\" to this._changedImages\n // - the next frame triggers a reload of this tile even though it already has the latest version\n this._updateTilesForChangedImages();\n\n const sourceCache = this.sourceCaches[params.source];\n if (sourceCache) {\n sourceCache.setDependencies(params.tileID.key, params.type, params.icons);\n }\n return images;\n }\n\n async getGlyphs(mapId: string | number, params: GetGlyphsParameters): Promise {\n const glypgs = await this.glyphManager.getGlyphs(params.stacks);\n const sourceCache = this.sourceCaches[params.source];\n if (sourceCache) {\n // we are not setting stacks as dependencies since for now\n // we just need to know which tiles have glyph dependencies\n sourceCache.setDependencies(params.tileID.key, params.type, ['']);\n }\n return glypgs;\n }\n\n getGlyphsUrl() {\n return this.stylesheet.glyphs || null;\n }\n\n setGlyphs(glyphsUrl: string | null, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n if (glyphsUrl && this._validate(validateStyle.glyphs, 'glyphs', glyphsUrl, null, options)) {\n return;\n }\n\n this._glyphsDidChange = true;\n this.stylesheet.glyphs = glyphsUrl;\n this.glyphManager.entries = {};\n this.glyphManager.setURL(glyphsUrl);\n }\n\n /**\n * Add a sprite.\n *\n * @param id - The id of the desired sprite\n * @param url - The url to load the desired sprite from\n * @param options - The style setter options\n * @param completion - The completion handler\n */\n addSprite(id: string, url: string, options: StyleSetterOptions = {}, completion?: (err: Error) => void) {\n this._checkLoaded();\n\n const spriteToAdd = [{id, url}];\n const updatedSprite = [\n ...coerceSpriteToArray(this.stylesheet.sprite),\n ...spriteToAdd\n ];\n\n if (this._validate(validateStyle.sprite, 'sprite', updatedSprite, null, options)) return;\n\n this.stylesheet.sprite = updatedSprite;\n this._loadSprite(spriteToAdd, true, completion);\n }\n\n /**\n * Remove a sprite by its id. When the last sprite is removed, the whole `this.stylesheet.sprite` object becomes\n * `undefined`. This falsy `undefined` value later prevents attempts to load the sprite when it's absent.\n *\n * @param id - the id of the sprite to remove\n */\n removeSprite(id: string) {\n this._checkLoaded();\n\n const internalSpriteRepresentation = coerceSpriteToArray(this.stylesheet.sprite);\n\n if (!internalSpriteRepresentation.find(sprite => sprite.id === id)) {\n this.fire(new ErrorEvent(new Error(`Sprite \"${id}\" doesn't exists on this map.`)));\n return;\n }\n\n if (this._spritesImagesIds[id]) {\n for (const imageId of this._spritesImagesIds[id]) {\n this.imageManager.removeImage(imageId);\n this._changedImages[imageId] = true;\n }\n }\n\n internalSpriteRepresentation.splice(internalSpriteRepresentation.findIndex(sprite => sprite.id === id), 1);\n this.stylesheet.sprite = internalSpriteRepresentation.length > 0 ? internalSpriteRepresentation : undefined;\n\n delete this._spritesImagesIds[id];\n this._availableImages = this.imageManager.listImages();\n this._changed = true;\n this.dispatcher.broadcast(MessageType.setImages, this._availableImages);\n this.fire(new Event('data', {dataType: 'style'}));\n }\n\n /**\n * Get the current sprite value.\n *\n * @returns empty array when no sprite is set; id-url pairs otherwise\n */\n getSprite() {\n return coerceSpriteToArray(this.stylesheet.sprite);\n }\n\n /**\n * Set a new value for the style's sprite.\n *\n * @param sprite - new sprite value\n * @param options - style setter options\n * @param completion - the completion handler\n */\n setSprite(sprite: SpriteSpecification, options: StyleSetterOptions = {}, completion?: (err: Error) => void) {\n this._checkLoaded();\n\n if (sprite && this._validate(validateStyle.sprite, 'sprite', sprite, null, options)) {\n return;\n }\n\n this.stylesheet.sprite = sprite;\n\n if (sprite) {\n this._loadSprite(sprite, true, completion);\n } else {\n this._unloadSprite();\n if (completion) {\n completion(null);\n }\n }\n }\n}\n","import {createLayout} from '../util/struct_array';\n\nexport default createLayout([\n {name: 'a_pos', type: 'Int16', components: 2}\n]);\n","\n// Disable Flow annotations here because Flow doesn't support importing GLSL files\n\nimport preludeFrag from './_prelude.fragment.glsl.g';\nimport preludeVert from './_prelude.vertex.glsl.g';\nimport backgroundFrag from './background.fragment.glsl.g';\nimport backgroundVert from './background.vertex.glsl.g';\nimport backgroundPatternFrag from './background_pattern.fragment.glsl.g';\nimport backgroundPatternVert from './background_pattern.vertex.glsl.g';\nimport circleFrag from './circle.fragment.glsl.g';\nimport circleVert from './circle.vertex.glsl.g';\nimport clippingMaskFrag from './clipping_mask.fragment.glsl.g';\nimport clippingMaskVert from './clipping_mask.vertex.glsl.g';\nimport heatmapFrag from './heatmap.fragment.glsl.g';\nimport heatmapVert from './heatmap.vertex.glsl.g';\nimport heatmapTextureFrag from './heatmap_texture.fragment.glsl.g';\nimport heatmapTextureVert from './heatmap_texture.vertex.glsl.g';\nimport collisionBoxFrag from './collision_box.fragment.glsl.g';\nimport collisionBoxVert from './collision_box.vertex.glsl.g';\nimport collisionCircleFrag from './collision_circle.fragment.glsl.g';\nimport collisionCircleVert from './collision_circle.vertex.glsl.g';\nimport debugFrag from './debug.fragment.glsl.g';\nimport debugVert from './debug.vertex.glsl.g';\nimport fillFrag from './fill.fragment.glsl.g';\nimport fillVert from './fill.vertex.glsl.g';\nimport fillOutlineFrag from './fill_outline.fragment.glsl.g';\nimport fillOutlineVert from './fill_outline.vertex.glsl.g';\nimport fillOutlinePatternFrag from './fill_outline_pattern.fragment.glsl.g';\nimport fillOutlinePatternVert from './fill_outline_pattern.vertex.glsl.g';\nimport fillPatternFrag from './fill_pattern.fragment.glsl.g';\nimport fillPatternVert from './fill_pattern.vertex.glsl.g';\nimport fillExtrusionFrag from './fill_extrusion.fragment.glsl.g';\nimport fillExtrusionVert from './fill_extrusion.vertex.glsl.g';\nimport fillExtrusionPatternFrag from './fill_extrusion_pattern.fragment.glsl.g';\nimport fillExtrusionPatternVert from './fill_extrusion_pattern.vertex.glsl.g';\nimport hillshadePrepareFrag from './hillshade_prepare.fragment.glsl.g';\nimport hillshadePrepareVert from './hillshade_prepare.vertex.glsl.g';\nimport hillshadeFrag from './hillshade.fragment.glsl.g';\nimport hillshadeVert from './hillshade.vertex.glsl.g';\nimport lineFrag from './line.fragment.glsl.g';\nimport lineVert from './line.vertex.glsl.g';\nimport lineGradientFrag from './line_gradient.fragment.glsl.g';\nimport lineGradientVert from './line_gradient.vertex.glsl.g';\nimport linePatternFrag from './line_pattern.fragment.glsl.g';\nimport linePatternVert from './line_pattern.vertex.glsl.g';\nimport lineSDFFrag from './line_sdf.fragment.glsl.g';\nimport lineSDFVert from './line_sdf.vertex.glsl.g';\nimport rasterFrag from './raster.fragment.glsl.g';\nimport rasterVert from './raster.vertex.glsl.g';\nimport symbolIconFrag from './symbol_icon.fragment.glsl.g';\nimport symbolIconVert from './symbol_icon.vertex.glsl.g';\nimport symbolSDFFrag from './symbol_sdf.fragment.glsl.g';\nimport symbolSDFVert from './symbol_sdf.vertex.glsl.g';\nimport symbolTextAndIconFrag from './symbol_text_and_icon.fragment.glsl.g';\nimport symbolTextAndIconVert from './symbol_text_and_icon.vertex.glsl.g';\nimport terrainDepthFrag from './terrain_depth.fragment.glsl.g';\nimport terrainCoordsFrag from './terrain_coords.fragment.glsl.g';\nimport terrainFrag from './terrain.fragment.glsl.g';\nimport terrainDepthVert from './terrain_depth.vertex.glsl.g';\nimport terrainCoordsVert from './terrain_coords.vertex.glsl.g';\nimport terrainVert from './terrain.vertex.glsl.g';\nimport skyFrag from './sky.fragment.glsl.g';\nimport skyVert from './sky.vertex.glsl.g';\n\nexport const shaders = {\n prelude: compile(preludeFrag, preludeVert),\n background: compile(backgroundFrag, backgroundVert),\n backgroundPattern: compile(backgroundPatternFrag, backgroundPatternVert),\n circle: compile(circleFrag, circleVert),\n clippingMask: compile(clippingMaskFrag, clippingMaskVert),\n heatmap: compile(heatmapFrag, heatmapVert),\n heatmapTexture: compile(heatmapTextureFrag, heatmapTextureVert),\n collisionBox: compile(collisionBoxFrag, collisionBoxVert),\n collisionCircle: compile(collisionCircleFrag, collisionCircleVert),\n debug: compile(debugFrag, debugVert),\n fill: compile(fillFrag, fillVert),\n fillOutline: compile(fillOutlineFrag, fillOutlineVert),\n fillOutlinePattern: compile(fillOutlinePatternFrag, fillOutlinePatternVert),\n fillPattern: compile(fillPatternFrag, fillPatternVert),\n fillExtrusion: compile(fillExtrusionFrag, fillExtrusionVert),\n fillExtrusionPattern: compile(fillExtrusionPatternFrag, fillExtrusionPatternVert),\n hillshadePrepare: compile(hillshadePrepareFrag, hillshadePrepareVert),\n hillshade: compile(hillshadeFrag, hillshadeVert),\n line: compile(lineFrag, lineVert),\n lineGradient: compile(lineGradientFrag, lineGradientVert),\n linePattern: compile(linePatternFrag, linePatternVert),\n lineSDF: compile(lineSDFFrag, lineSDFVert),\n raster: compile(rasterFrag, rasterVert),\n symbolIcon: compile(symbolIconFrag, symbolIconVert),\n symbolSDF: compile(symbolSDFFrag, symbolSDFVert),\n symbolTextAndIcon: compile(symbolTextAndIconFrag, symbolTextAndIconVert),\n terrain: compile(terrainFrag, terrainVert),\n terrainDepth: compile(terrainDepthFrag, terrainDepthVert),\n terrainCoords: compile(terrainCoordsFrag, terrainCoordsVert),\n sky: compile(skyFrag, skyVert)};\n\n// Expand #pragmas to #ifdefs.\n\nfunction compile(fragmentSource, vertexSource) {\n const re = /#pragma mapbox: ([\\w]+) ([\\w]+) ([\\w]+) ([\\w]+)/g;\n\n const staticAttributes = vertexSource.match(/attribute ([\\w]+) ([\\w]+)/g);\n const fragmentUniforms = fragmentSource.match(/uniform ([\\w]+) ([\\w]+)([\\s]*)([\\w]*)/g);\n const vertexUniforms = vertexSource.match(/uniform ([\\w]+) ([\\w]+)([\\s]*)([\\w]*)/g);\n const staticUniforms = vertexUniforms ? vertexUniforms.concat(fragmentUniforms) : fragmentUniforms;\n\n const fragmentPragmas = {};\n\n fragmentSource = fragmentSource.replace(re, (match, operation, precision, type, name) => {\n fragmentPragmas[name] = true;\n if (operation === 'define') {\n return `\n#ifndef HAS_UNIFORM_u_${name}\nvarying ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`;\n } else /* if (operation === 'initialize') */ {\n return `\n#ifdef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n }\n });\n\n vertexSource = vertexSource.replace(re, (match, operation, precision, type, name) => {\n const attrType = type === 'float' ? 'vec2' : 'vec4';\n const unpackType = name.match(/color/) ? 'color' : attrType;\n\n if (fragmentPragmas[name]) {\n if (operation === 'define') {\n return `\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nattribute ${precision} ${attrType} a_${name};\nvarying ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`;\n } else /* if (operation === 'initialize') */ {\n if (unpackType === 'vec4') {\n // vec4 attributes are only used for cross-faded properties, and are not packed\n return `\n#ifndef HAS_UNIFORM_u_${name}\n ${name} = a_${name};\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n } else {\n return `\n#ifndef HAS_UNIFORM_u_${name}\n ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n }\n }\n } else {\n if (operation === 'define') {\n return `\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nattribute ${precision} ${attrType} a_${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`;\n } else /* if (operation === 'initialize') */ {\n if (unpackType === 'vec4') {\n // vec4 attributes are only used for cross-faded properties, and are not packed\n return `\n#ifndef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = a_${name};\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n } else /* */ {\n return `\n#ifndef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n }\n }\n }\n });\n\n return {fragmentSource, vertexSource, staticAttributes, staticUniforms};\n}\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision mediump float;\\n#else\\n#if !defined(lowp)\\n#define lowp\\n#endif\\n#if !defined(mediump)\\n#define mediump\\n#endif\\n#if !defined(highp)\\n#define highp\\n#endif\\n#endif\\n';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#else\\n#if !defined(lowp)\\n#define lowp\\n#endif\\n#if !defined(mediump)\\n#define mediump\\n#endif\\n#if !defined(highp)\\n#define highp\\n#endif\\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(unpack_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;}\\n#ifdef TERRAIN3D\\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\\n#endif\\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\\n#ifdef TERRAIN3D\\nhighp float d=unpack(texture2D(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\\n#else\\nreturn 1.0;\\n#endif\\n}float calculate_visibility(vec4 pos) {\\n#ifdef TERRAIN3D\\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\\n#else\\nreturn 1.0;\\n#endif\\n}float ele(vec2 pos) {\\n#ifdef TERRAIN3D\\nvec4 rgb=(texture2D(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\\n#else\\nreturn 0.0;\\n#endif\\n}float get_elevation(vec2 pos) {\\n#ifdef TERRAIN3D\\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\\n#else\\nreturn 0.0;\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'varying vec3 v_data;varying 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\\nvoid 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);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;varying 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\\nvoid 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);float ele=get_elevation(circle_center);v_visibility=calculate_visibility(u_matrix*vec4(circle_center,ele,1.0));if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,ele,1);} else {gl_Position=u_matrix*vec4(circle_center,ele,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'void main() {gl_FragColor=vec4(1.0);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform highp float u_intensity;varying 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);gl_FragColor=vec4(val,1.0,1.0,1.0);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying 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;vec4 pos=vec4(floor(a_pos*0.5)+extrude,get_elevation(floor(a_pos*0.5)),1);gl_Position=u_matrix*pos;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(0.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec2 a_anchor_pos;attribute vec2 a_placed;attribute vec2 a_box_real;uniform mat4 u_matrix;uniform vec2 u_pixel_extrude_scale;varying float v_placed;varying float v_notUsed;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying 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);gl_FragColor=color*alpha*opacity_t;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying 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;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-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(0.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);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,get_elevation(a_pos),1);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#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_FragColor=color*opacity;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute 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","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'varying 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\\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying 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","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp vec4 pattern_from\\n#pragma mapbox: define lowp vec4 pattern_to\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump vec4 pattern_from\\n#pragma mapbox: initialize mediump vec4 pattern_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp vec4 pattern_from\\n#pragma mapbox: define lowp vec4 pattern_to\\n#pragma mapbox: define lowp float pixel_ratio_from\\n#pragma mapbox: define lowp float pixel_ratio_to\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump vec4 pattern_from\\n#pragma mapbox: initialize mediump vec4 pattern_to\\n#pragma mapbox: initialize lowp float pixel_ratio_from\\n#pragma mapbox: initialize lowp float pixel_ratio_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#endif\\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp vec4 pattern_from\\n#pragma mapbox: define lowp vec4 pattern_to\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump vec4 pattern_from\\n#pragma mapbox: initialize mediump vec4 pattern_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp vec4 pattern_from\\n#pragma mapbox: define lowp vec4 pattern_to\\n#pragma mapbox: define lowp float pixel_ratio_from\\n#pragma mapbox: define lowp float pixel_ratio_to\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump vec4 pattern_from\\n#pragma mapbox: initialize mediump vec4 pattern_to\\n#pragma mapbox: initialize lowp float pixel_ratio_from\\n#pragma mapbox: initialize lowp float pixel_ratio_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'varying vec4 v_color;void main() {gl_FragColor=v_color;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform 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;attribute vec2 a_pos;attribute vec4 a_normal_ed;\\n#ifdef TERRAIN3D\\nattribute vec2 a_centroid;\\n#endif\\nvarying vec4 v_color;\\n#pragma mapbox: define highp float base\\n#pragma mapbox: define highp float height\\n#pragma mapbox: define highp vec4 color\\nvoid main() {\\n#pragma mapbox: initialize highp float base\\n#pragma mapbox: initialize highp float height\\n#pragma mapbox: initialize highp vec4 color\\nvec3 normal=a_normal_ed.xyz;\\n#ifdef TERRAIN3D\\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\\n#else\\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\\n#endif\\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\\n#pragma mapbox: define lowp float base\\n#pragma mapbox: define lowp float height\\n#pragma mapbox: define lowp vec4 pattern_from\\n#pragma mapbox: define lowp vec4 pattern_to\\n#pragma mapbox: define lowp float pixel_ratio_from\\n#pragma mapbox: define lowp float pixel_ratio_to\\nvoid main() {\\n#pragma mapbox: initialize lowp float base\\n#pragma mapbox: initialize lowp float height\\n#pragma mapbox: initialize mediump vec4 pattern_from\\n#pragma mapbox: initialize mediump vec4 pattern_to\\n#pragma mapbox: initialize lowp float pixel_ratio_from\\n#pragma mapbox: initialize lowp float pixel_ratio_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\\n#ifdef TERRAIN3D\\nattribute vec2 a_centroid;\\n#endif\\nvarying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\\n#pragma mapbox: define lowp float base\\n#pragma mapbox: define lowp float height\\n#pragma mapbox: define lowp vec4 pattern_from\\n#pragma mapbox: define lowp vec4 pattern_to\\n#pragma mapbox: define lowp float pixel_ratio_from\\n#pragma mapbox: define lowp float pixel_ratio_to\\nvoid main() {\\n#pragma mapbox: initialize lowp float base\\n#pragma mapbox: initialize lowp float height\\n#pragma mapbox: initialize mediump vec4 pattern_from\\n#pragma mapbox: initialize mediump vec4 pattern_to\\n#pragma mapbox: initialize lowp float pixel_ratio_from\\n#pragma mapbox: initialize lowp float pixel_ratio_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\\n#ifdef TERRAIN3D\\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\\n#else\\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\\n#endif\\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\\n? a_pos\\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#endif\\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);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((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying 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;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\\n#define PI 3.141592653589793\\nvoid main() {vec4 pixel=texture2D(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);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\\n#pragma mapbox: define highp vec4 color\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 color\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\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);gl_FragColor=color*(alpha*opacity);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\n#define scale 0.015873016\\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\\n#pragma mapbox: define highp vec4 color\\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\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 color\\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\\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;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.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_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\\n#ifdef TERRAIN3D\\nv_gamma_scale=1.0;\\n#else\\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#endif\\nv_width2=vec2(outset,inset);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\nvoid main() {\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\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);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\n#define scale 0.015873016\\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\\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\\nvoid main() {\\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\\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;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);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_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\\n#ifdef TERRAIN3D\\nv_gamma_scale=1.0;\\n#else\\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#endif\\nv_width2=vec2(outset,inset);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#endif\\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\\n#pragma mapbox: define lowp vec4 pattern_from\\n#pragma mapbox: define lowp vec4 pattern_to\\n#pragma mapbox: define lowp float pixel_ratio_from\\n#pragma mapbox: define lowp float pixel_ratio_to\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\nvoid main() {\\n#pragma mapbox: initialize mediump vec4 pattern_from\\n#pragma mapbox: initialize mediump vec4 pattern_to\\n#pragma mapbox: initialize lowp float pixel_ratio_from\\n#pragma mapbox: initialize lowp float pixel_ratio_to\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.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 x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\n#define scale 0.015873016\\n#define LINE_DISTANCE_SCALE 2.0\\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying 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_from\\n#pragma mapbox: define lowp vec4 pattern_to\\n#pragma mapbox: define lowp float pixel_ratio_from\\n#pragma mapbox: define lowp float pixel_ratio_to\\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_from\\n#pragma mapbox: initialize mediump vec4 pattern_to\\n#pragma mapbox: initialize lowp float pixel_ratio_from\\n#pragma mapbox: initialize lowp float pixel_ratio_to\\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;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;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_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\\n#ifdef TERRAIN3D\\nv_gamma_scale=1.0;\\n#else\\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#endif\\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\\n#pragma mapbox: define highp vec4 color\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define mediump float width\\n#pragma mapbox: define lowp float floorwidth\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 color\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump float width\\n#pragma mapbox: initialize lowp float floorwidth\\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);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\n#define scale 0.015873016\\n#define LINE_DISTANCE_SCALE 2.0\\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\\n#pragma mapbox: define highp vec4 color\\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 floorwidth\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 color\\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 floorwidth\\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;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;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_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\\n#ifdef TERRAIN3D\\nv_gamma_scale=1.0;\\n#else\\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#endif\\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;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;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(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);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\\n#pragma mapbox: define lowp float opacity\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform 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 highp float u_pitch;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 bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_tex;varying float v_fade_opacity;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\\n#pragma mapbox: define lowp float opacity\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];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 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.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(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp 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);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#define SDF_PX 8.0\\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying 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\\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\\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 inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}gl_FragColor=color*(alpha*opacity*fade_opacity);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform 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_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;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 vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_data0;varying vec3 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\\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\\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\\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];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 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.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(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp 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);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#define SDF_PX 8.0\\n#define SDF 1.0\\n#define ICON 0.0\\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying 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\\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\\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=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;if (u_is_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=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\\n#ifdef OVERDRAW_INSPECTOR\\ngl_FragColor=vec4(1.0);\\n#endif\\n}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform 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 highp float u_pitch;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 vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec4 v_data0;varying vec4 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\\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\\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\\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];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 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.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(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp 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);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;varying vec2 v_texture_pos;varying float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture2D(u_texture,v_texture_pos);if (v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);gl_FragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {gl_FragColor=surface_color;}}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform mat4 u_fog_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'varying float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {gl_FragColor=pack(v_depth);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);v_depth=gl_Position.z/gl_Position.w;}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;varying vec2 v_texture_pos;void main() {vec4 rgba=texture2D(u_texture,v_texture_pos);gl_FragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform float u_horizon;uniform float u_sky_horizon_blend;void main() {float y=gl_FragCoord.y;if (y > u_horizon) {float blend=y-u_horizon;if (blend < u_sky_horizon_blend) {gl_FragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {gl_FragColor=u_sky_color;}}}';\n","// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'attribute vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}';\n","\nimport type {Program} from './program';\nimport type {VertexBuffer} from '../gl/vertex_buffer';\nimport type {IndexBuffer} from '../gl/index_buffer';\nimport type {Context} from '../gl/context';\n\n/**\n * @internal\n * A vertex array object used to pass data to the webgl code\n */\nexport class VertexArrayObject {\n context: Context;\n boundProgram: Program;\n boundLayoutVertexBuffer: VertexBuffer;\n boundPaintVertexBuffers: Array;\n boundIndexBuffer: IndexBuffer;\n boundVertexOffset: number;\n boundDynamicVertexBuffer: VertexBuffer;\n boundDynamicVertexBuffer2: VertexBuffer;\n boundDynamicVertexBuffer3: VertexBuffer;\n vao: any;\n\n constructor() {\n this.boundProgram = null;\n this.boundLayoutVertexBuffer = null;\n this.boundPaintVertexBuffers = [];\n this.boundIndexBuffer = null;\n this.boundVertexOffset = null;\n this.boundDynamicVertexBuffer = null;\n this.vao = null;\n }\n\n bind(context: Context,\n program: Program,\n layoutVertexBuffer: VertexBuffer,\n paintVertexBuffers: Array,\n indexBuffer?: IndexBuffer | null,\n vertexOffset?: number | null,\n dynamicVertexBuffer?: VertexBuffer | null,\n dynamicVertexBuffer2?: VertexBuffer | null,\n dynamicVertexBuffer3?: VertexBuffer | null) {\n\n this.context = context;\n\n let paintBuffersDiffer = this.boundPaintVertexBuffers.length !== paintVertexBuffers.length;\n for (let i = 0; !paintBuffersDiffer && i < paintVertexBuffers.length; i++) {\n if (this.boundPaintVertexBuffers[i] !== paintVertexBuffers[i]) {\n paintBuffersDiffer = true;\n }\n }\n\n const isFreshBindRequired = (\n !this.vao ||\n this.boundProgram !== program ||\n this.boundLayoutVertexBuffer !== layoutVertexBuffer ||\n paintBuffersDiffer ||\n this.boundIndexBuffer !== indexBuffer ||\n this.boundVertexOffset !== vertexOffset ||\n this.boundDynamicVertexBuffer !== dynamicVertexBuffer ||\n this.boundDynamicVertexBuffer2 !== dynamicVertexBuffer2 ||\n this.boundDynamicVertexBuffer3 !== dynamicVertexBuffer3\n );\n\n if (isFreshBindRequired) {\n this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3);\n } else {\n context.bindVertexArray.set(this.vao);\n\n if (dynamicVertexBuffer) {\n // The buffer may have been updated. Rebind to upload data.\n dynamicVertexBuffer.bind();\n }\n\n if (indexBuffer && indexBuffer.dynamicDraw) {\n indexBuffer.bind();\n }\n\n if (dynamicVertexBuffer2) {\n dynamicVertexBuffer2.bind();\n }\n\n if (dynamicVertexBuffer3) {\n dynamicVertexBuffer3.bind();\n }\n }\n }\n\n freshBind(program: Program,\n layoutVertexBuffer: VertexBuffer,\n paintVertexBuffers: Array,\n indexBuffer?: IndexBuffer | null,\n vertexOffset?: number | null,\n dynamicVertexBuffer?: VertexBuffer | null,\n dynamicVertexBuffer2?: VertexBuffer | null,\n dynamicVertexBuffer3?: VertexBuffer | null) {\n\n const numNextAttributes = program.numAttributes;\n\n const context = this.context;\n const gl = context.gl;\n\n if (this.vao) this.destroy();\n this.vao = context.createVertexArray();\n context.bindVertexArray.set(this.vao);\n\n // store the arguments so that we can verify them when the vao is bound again\n this.boundProgram = program;\n this.boundLayoutVertexBuffer = layoutVertexBuffer;\n this.boundPaintVertexBuffers = paintVertexBuffers;\n this.boundIndexBuffer = indexBuffer;\n this.boundVertexOffset = vertexOffset;\n this.boundDynamicVertexBuffer = dynamicVertexBuffer;\n this.boundDynamicVertexBuffer2 = dynamicVertexBuffer2;\n this.boundDynamicVertexBuffer3 = dynamicVertexBuffer3;\n\n layoutVertexBuffer.enableAttributes(gl, program);\n for (const vertexBuffer of paintVertexBuffers) {\n vertexBuffer.enableAttributes(gl, program);\n }\n\n if (dynamicVertexBuffer) {\n dynamicVertexBuffer.enableAttributes(gl, program);\n }\n if (dynamicVertexBuffer2) {\n dynamicVertexBuffer2.enableAttributes(gl, program);\n }\n if (dynamicVertexBuffer3) {\n dynamicVertexBuffer3.enableAttributes(gl, program);\n }\n\n layoutVertexBuffer.bind();\n layoutVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);\n for (const vertexBuffer of paintVertexBuffers) {\n vertexBuffer.bind();\n vertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);\n }\n\n if (dynamicVertexBuffer) {\n dynamicVertexBuffer.bind();\n dynamicVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);\n }\n if (indexBuffer) {\n indexBuffer.bind();\n }\n if (dynamicVertexBuffer2) {\n dynamicVertexBuffer2.bind();\n dynamicVertexBuffer2.setVertexAttribPointers(gl, program, vertexOffset);\n }\n if (dynamicVertexBuffer3) {\n dynamicVertexBuffer3.bind();\n dynamicVertexBuffer3.setVertexAttribPointers(gl, program, vertexOffset);\n }\n\n context.currentNumAttributes = numNextAttributes;\n }\n\n destroy() {\n if (this.vao) {\n this.context.deleteVertexArray(this.vao);\n this.vao = null;\n }\n }\n}\n","import {\n Uniform1i,\n Uniform1f,\n Uniform4f,\n UniformMatrix4f,\n UniformColor\n} from '../uniform_binding';\nimport type {Context} from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../../render/uniform_binding';\nimport {mat4} from 'gl-matrix';\nimport {Sky} from '../../style/sky';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\n\nexport type TerrainPreludeUniformsType = {\n 'u_depth': Uniform1i;\n 'u_terrain': Uniform1i;\n 'u_terrain_dim': Uniform1f;\n 'u_terrain_matrix': UniformMatrix4f;\n 'u_terrain_unpack': Uniform4f;\n 'u_terrain_exaggeration': Uniform1f;\n};\n\nexport type TerrainUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_texture': Uniform1i;\n 'u_ele_delta': Uniform1f;\n 'u_fog_matrix': UniformMatrix4f;\n 'u_fog_color': UniformColor;\n 'u_fog_ground_blend': Uniform1f;\n 'u_fog_ground_blend_opacity': Uniform1f;\n 'u_horizon_color': UniformColor;\n 'u_horizon_fog_blend': Uniform1f;\n};\n\nexport type TerrainDepthUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_ele_delta': Uniform1f;\n};\n\nexport type TerrainCoordsUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_texture': Uniform1i;\n 'u_terrain_coords_id': Uniform1f;\n 'u_ele_delta': Uniform1f;\n};\n\nconst terrainPreludeUniforms = (context: Context, locations: UniformLocations): TerrainPreludeUniformsType => ({\n 'u_depth': new Uniform1i(context, locations.u_depth),\n 'u_terrain': new Uniform1i(context, locations.u_terrain),\n 'u_terrain_dim': new Uniform1f(context, locations.u_terrain_dim),\n 'u_terrain_matrix': new UniformMatrix4f(context, locations.u_terrain_matrix),\n 'u_terrain_unpack': new Uniform4f(context, locations.u_terrain_unpack),\n 'u_terrain_exaggeration': new Uniform1f(context, locations.u_terrain_exaggeration)\n});\n\nconst terrainUniforms = (context: Context, locations: UniformLocations): TerrainUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_texture': new Uniform1i(context, locations.u_texture),\n 'u_ele_delta': new Uniform1f(context, locations.u_ele_delta),\n 'u_fog_matrix': new UniformMatrix4f(context, locations.u_fog_matrix),\n 'u_fog_color': new UniformColor(context, locations.u_fog_color),\n 'u_fog_ground_blend': new Uniform1f(context, locations.u_fog_ground_blend),\n 'u_fog_ground_blend_opacity': new Uniform1f(context, locations.u_fog_ground_blend_opacity),\n 'u_horizon_color': new UniformColor(context, locations.u_horizon_color),\n 'u_horizon_fog_blend': new Uniform1f(context, locations.u_horizon_fog_blend)\n});\n\nconst terrainDepthUniforms = (context: Context, locations: UniformLocations): TerrainDepthUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_ele_delta': new Uniform1f(context, locations.u_ele_delta)\n});\n\nconst terrainCoordsUniforms = (context: Context, locations: UniformLocations): TerrainCoordsUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_texture': new Uniform1i(context, locations.u_texture),\n 'u_terrain_coords_id': new Uniform1f(context, locations.u_terrain_coords_id),\n 'u_ele_delta': new Uniform1f(context, locations.u_ele_delta)\n});\n\nconst terrainUniformValues = (\n matrix: mat4,\n eleDelta: number,\n fogMatrix: mat4,\n sky: Sky,\n pitch: number): UniformValues => ({\n 'u_matrix': matrix,\n 'u_texture': 0,\n 'u_ele_delta': eleDelta,\n 'u_fog_matrix': fogMatrix,\n 'u_fog_color': sky ? sky.properties.get('fog-color') : Color.white,\n 'u_fog_ground_blend': sky ? sky.properties.get('fog-ground-blend') : 1,\n 'u_fog_ground_blend_opacity': sky ? sky.calculateFogBlendOpacity(pitch) : 0,\n 'u_horizon_color': sky ? sky.properties.get('horizon-color') : Color.white,\n 'u_horizon_fog_blend': sky ? sky.properties.get('horizon-fog-blend') : 1\n});\n\nconst terrainDepthUniformValues = (\n matrix: mat4,\n eleDelta: number\n): UniformValues => ({\n 'u_matrix': matrix,\n 'u_ele_delta': eleDelta\n});\n\nconst terrainCoordsUniformValues = (\n matrix: mat4,\n coordsId: number,\n eleDelta: number\n): UniformValues => ({\n 'u_matrix': matrix,\n 'u_terrain_coords_id': coordsId / 255,\n 'u_texture': 0,\n 'u_ele_delta': eleDelta\n});\n\nexport {terrainUniforms, terrainDepthUniforms, terrainCoordsUniforms, terrainPreludeUniforms, terrainUniformValues, terrainDepthUniformValues, terrainCoordsUniformValues};\n","import {shaders} from '../shaders/shaders';\nimport {ProgramConfiguration} from '../data/program_configuration';\nimport {VertexArrayObject} from './vertex_array_object';\nimport {Context} from '../gl/context';\n\nimport type {SegmentVector} from '../data/segment';\nimport type {VertexBuffer} from '../gl/vertex_buffer';\nimport type {IndexBuffer} from '../gl/index_buffer';\nimport type {DepthMode} from '../gl/depth_mode';\nimport type {StencilMode} from '../gl/stencil_mode';\nimport type {ColorMode} from '../gl/color_mode';\nimport type {CullFaceMode} from '../gl/cull_face_mode';\nimport type {UniformBindings, UniformValues, UniformLocations} from './uniform_binding';\nimport type {BinderUniform} from '../data/program_configuration';\nimport {terrainPreludeUniforms, TerrainPreludeUniformsType} from './program/terrain_program';\nimport type {TerrainData} from '../render/terrain';\nimport {Terrain} from '../render/terrain';\n\nexport type DrawMode = WebGLRenderingContextBase['LINES'] | WebGLRenderingContextBase['TRIANGLES'] | WebGL2RenderingContext['LINE_STRIP'];\n\nfunction getTokenizedAttributesAndUniforms(array: Array): Array {\n const result = [];\n\n for (let i = 0; i < array.length; i++) {\n if (array[i] === null) continue;\n const token = array[i].split(' ');\n result.push(token.pop());\n }\n return result;\n}\n\n/**\n * @internal\n * A webgl program to execute in the GPU space\n */\nexport class Program {\n program: WebGLProgram;\n attributes: {[_: string]: number};\n numAttributes: number;\n fixedUniforms: Us;\n terrainUniforms: TerrainPreludeUniformsType;\n binderUniforms: Array;\n failedToCreate: boolean;\n\n constructor(context: Context,\n source: {\n fragmentSource: string;\n vertexSource: string;\n staticAttributes: Array;\n staticUniforms: Array;\n },\n configuration: ProgramConfiguration,\n fixedUniforms: (b: Context, a: UniformLocations) => Us,\n showOverdrawInspector: boolean,\n terrain: Terrain) {\n\n const gl = context.gl;\n this.program = gl.createProgram();\n\n const staticAttrInfo = getTokenizedAttributesAndUniforms(source.staticAttributes);\n const dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : [];\n const allAttrInfo = staticAttrInfo.concat(dynamicAttrInfo);\n\n const preludeUniformsInfo = shaders.prelude.staticUniforms ? getTokenizedAttributesAndUniforms(shaders.prelude.staticUniforms) : [];\n const staticUniformsInfo = source.staticUniforms ? getTokenizedAttributesAndUniforms(source.staticUniforms) : [];\n const dynamicUniformsInfo = configuration ? configuration.getBinderUniforms() : [];\n // remove duplicate uniforms\n const uniformList = preludeUniformsInfo.concat(staticUniformsInfo).concat(dynamicUniformsInfo);\n const allUniformsInfo = [];\n for (const uniform of uniformList) {\n if (allUniformsInfo.indexOf(uniform) < 0) allUniformsInfo.push(uniform);\n }\n\n const defines = configuration ? configuration.defines() : [];\n if (showOverdrawInspector) {\n defines.push('#define OVERDRAW_INSPECTOR;');\n }\n if (terrain) {\n defines.push('#define TERRAIN3D;');\n }\n\n const fragmentSource = defines.concat(shaders.prelude.fragmentSource, source.fragmentSource).join('\\n');\n const vertexSource = defines.concat(shaders.prelude.vertexSource, source.vertexSource).join('\\n');\n\n const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n if (gl.isContextLost()) {\n this.failedToCreate = true;\n return;\n }\n gl.shaderSource(fragmentShader, fragmentSource);\n gl.compileShader(fragmentShader);\n\n if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {\n throw new Error(`Could not compile fragment shader: ${gl.getShaderInfoLog(fragmentShader)}`);\n }\n\n gl.attachShader(this.program, fragmentShader);\n\n const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n if (gl.isContextLost()) {\n this.failedToCreate = true;\n return;\n }\n gl.shaderSource(vertexShader, vertexSource);\n gl.compileShader(vertexShader);\n\n if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {\n throw new Error(`Could not compile vertex shader: ${gl.getShaderInfoLog(vertexShader)}`);\n }\n\n gl.attachShader(this.program, vertexShader);\n\n this.attributes = {};\n const uniformLocations = {};\n\n this.numAttributes = allAttrInfo.length;\n\n for (let i = 0; i < this.numAttributes; i++) {\n if (allAttrInfo[i]) {\n gl.bindAttribLocation(this.program, i, allAttrInfo[i]);\n this.attributes[allAttrInfo[i]] = i;\n }\n }\n\n gl.linkProgram(this.program);\n\n if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) {\n throw new Error(`Program failed to link: ${gl.getProgramInfoLog(this.program)}`);\n }\n\n gl.deleteShader(vertexShader);\n gl.deleteShader(fragmentShader);\n\n for (let it = 0; it < allUniformsInfo.length; it++) {\n const uniform = allUniformsInfo[it];\n if (uniform && !uniformLocations[uniform]) {\n const uniformLocation = gl.getUniformLocation(this.program, uniform);\n if (uniformLocation) {\n uniformLocations[uniform] = uniformLocation;\n }\n }\n }\n\n this.fixedUniforms = fixedUniforms(context, uniformLocations);\n this.terrainUniforms = terrainPreludeUniforms(context, uniformLocations);\n this.binderUniforms = configuration ? configuration.getUniforms(context, uniformLocations) : [];\n }\n\n draw(context: Context,\n drawMode: DrawMode,\n depthMode: Readonly,\n stencilMode: Readonly,\n colorMode: Readonly,\n cullFaceMode: Readonly,\n uniformValues: UniformValues,\n terrain: TerrainData,\n layerID: string,\n layoutVertexBuffer: VertexBuffer,\n indexBuffer: IndexBuffer,\n segments: SegmentVector,\n currentProperties?: any,\n zoom?: number | null,\n configuration?: ProgramConfiguration | null,\n dynamicLayoutBuffer?: VertexBuffer | null,\n dynamicLayoutBuffer2?: VertexBuffer | null,\n dynamicLayoutBuffer3?: VertexBuffer | null) {\n\n const gl = context.gl;\n\n if (this.failedToCreate) return;\n\n context.program.set(this.program);\n context.setDepthMode(depthMode);\n context.setStencilMode(stencilMode);\n context.setColorMode(colorMode);\n context.setCullFace(cullFaceMode);\n\n // set variables used by the 3d functions defined in _prelude.vertex.glsl\n if (terrain) {\n context.activeTexture.set(gl.TEXTURE2);\n gl.bindTexture(gl.TEXTURE_2D, terrain.depthTexture);\n context.activeTexture.set(gl.TEXTURE3);\n gl.bindTexture(gl.TEXTURE_2D, terrain.texture);\n for (const name in this.terrainUniforms) {\n this.terrainUniforms[name].set(terrain[name]);\n }\n }\n\n for (const name in this.fixedUniforms) {\n this.fixedUniforms[name].set(uniformValues[name]);\n }\n\n if (configuration) {\n configuration.setUniforms(context, this.binderUniforms, currentProperties, {zoom: (zoom as any)});\n }\n\n let primitiveSize = 0;\n switch (drawMode) {\n case gl.LINES:\n primitiveSize = 2;\n break;\n case gl.TRIANGLES:\n primitiveSize = 3;\n break;\n case gl.LINE_STRIP:\n primitiveSize = 1;\n break;\n }\n\n for (const segment of segments.get()) {\n const vaos = segment.vaos || (segment.vaos = {});\n const vao: VertexArrayObject = vaos[layerID] || (vaos[layerID] = new VertexArrayObject());\n\n vao.bind(\n context,\n this,\n layoutVertexBuffer,\n configuration ? configuration.getPaintVertexBuffers() : [],\n indexBuffer,\n segment.vertexOffset,\n dynamicLayoutBuffer,\n dynamicLayoutBuffer2,\n dynamicLayoutBuffer3\n );\n\n gl.drawElements(\n drawMode,\n segment.primitiveLength * primitiveSize,\n gl.UNSIGNED_SHORT,\n segment.primitiveOffset * primitiveSize * 2);\n }\n }\n}\n","import {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f\n} from '../uniform_binding';\nimport {pixelsToTileUnits} from '../../source/pixels_to_tile_units';\n\nimport type {Painter} from '../painter';\nimport type {OverscaledTileID} from '../../source/tile_id';\nimport type {CrossFaded} from '../../style/properties';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport type {UniformValues} from '../uniform_binding';\nimport type {Tile} from '../../source/tile';\nimport type {ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\n\ntype BackgroundPatternUniformsType = {\n 'u_image': Uniform1i;\n 'u_pattern_tl_a': Uniform2f;\n 'u_pattern_br_a': Uniform2f;\n 'u_pattern_tl_b': Uniform2f;\n 'u_pattern_br_b': Uniform2f;\n 'u_texsize': Uniform2f;\n 'u_mix': Uniform1f;\n 'u_pattern_size_a': Uniform2f;\n 'u_pattern_size_b': Uniform2f;\n 'u_scale_a': Uniform1f;\n 'u_scale_b': Uniform1f;\n 'u_pixel_coord_upper': Uniform2f;\n 'u_pixel_coord_lower': Uniform2f;\n 'u_tile_units_to_pixels': Uniform1f;\n};\n\nexport type PatternUniformsType = {\n // pattern uniforms:\n 'u_image': Uniform1i;\n 'u_texsize': Uniform2f;\n 'u_scale': Uniform3f;\n 'u_fade': Uniform1f;\n 'u_pixel_coord_upper': Uniform2f;\n 'u_pixel_coord_lower': Uniform2f;\n};\n\nfunction patternUniformValues(crossfade: CrossfadeParameters, painter: Painter, tile: Tile): UniformValues {\n\n const tileRatio = 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom);\n\n const numTiles = Math.pow(2, tile.tileID.overscaledZ);\n const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;\n\n const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);\n const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;\n\n return {\n 'u_image': 0,\n 'u_texsize': tile.imageAtlasTexture.size,\n 'u_scale': [tileRatio, crossfade.fromScale, crossfade.toScale],\n 'u_fade': crossfade.t,\n // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision.\n 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16],\n 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF]\n };\n}\n\nfunction bgPatternUniformValues(\n image: CrossFaded,\n crossfade: CrossfadeParameters,\n painter: Painter,\n tile: {\n tileID: OverscaledTileID;\n tileSize: number;\n }\n): UniformValues {\n const imagePosA = painter.imageManager.getPattern(image.from.toString());\n const imagePosB = painter.imageManager.getPattern(image.to.toString());\n const {width, height} = painter.imageManager.getPixelSize();\n\n const numTiles = Math.pow(2, tile.tileID.overscaledZ);\n const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;\n\n const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);\n const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;\n\n return {\n 'u_image': 0,\n 'u_pattern_tl_a': (imagePosA as any).tl,\n 'u_pattern_br_a': (imagePosA as any).br,\n 'u_pattern_tl_b': (imagePosB as any).tl,\n 'u_pattern_br_b': (imagePosB as any).br,\n 'u_texsize': [width, height],\n 'u_mix': crossfade.t,\n 'u_pattern_size_a': (imagePosA as any).displaySize,\n 'u_pattern_size_b': (imagePosB as any).displaySize,\n 'u_scale_a': crossfade.fromScale,\n 'u_scale_b': crossfade.toScale,\n 'u_tile_units_to_pixels': 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom),\n // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision.\n 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16],\n 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF]\n };\n}\nexport {bgPatternUniformValues, patternUniformValues};\n","import {patternUniformValues} from './pattern';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n UniformMatrix4f\n} from '../uniform_binding';\n\nimport {mat3, mat4, vec3} from 'gl-matrix';\nimport {extend} from '../../util/util';\n\nimport type {Context} from '../../gl/context';\nimport type {Painter} from '../painter';\nimport type {OverscaledTileID} from '../../source/tile_id';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport type {Tile} from '../../source/tile';\n\nexport type FillExtrusionUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_lightpos': Uniform3f;\n 'u_lightintensity': Uniform1f;\n 'u_lightcolor': Uniform3f;\n 'u_vertical_gradient': Uniform1f;\n 'u_opacity': Uniform1f;\n};\n\nexport type FillExtrusionPatternUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_lightpos': Uniform3f;\n 'u_lightintensity': Uniform1f;\n 'u_lightcolor': Uniform3f;\n 'u_height_factor': Uniform1f;\n 'u_vertical_gradient': Uniform1f;\n // pattern uniforms:\n 'u_texsize': Uniform2f;\n 'u_image': Uniform1i;\n 'u_pixel_coord_upper': Uniform2f;\n 'u_pixel_coord_lower': Uniform2f;\n 'u_scale': Uniform3f;\n 'u_fade': Uniform1f;\n 'u_opacity': Uniform1f;\n};\n\nconst fillExtrusionUniforms = (context: Context, locations: UniformLocations): FillExtrusionUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_lightpos': new Uniform3f(context, locations.u_lightpos),\n 'u_lightintensity': new Uniform1f(context, locations.u_lightintensity),\n 'u_lightcolor': new Uniform3f(context, locations.u_lightcolor),\n 'u_vertical_gradient': new Uniform1f(context, locations.u_vertical_gradient),\n 'u_opacity': new Uniform1f(context, locations.u_opacity)\n});\n\nconst fillExtrusionPatternUniforms = (context: Context, locations: UniformLocations): FillExtrusionPatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_lightpos': new Uniform3f(context, locations.u_lightpos),\n 'u_lightintensity': new Uniform1f(context, locations.u_lightintensity),\n 'u_lightcolor': new Uniform3f(context, locations.u_lightcolor),\n 'u_vertical_gradient': new Uniform1f(context, locations.u_vertical_gradient),\n 'u_height_factor': new Uniform1f(context, locations.u_height_factor),\n // pattern uniforms\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n 'u_scale': new Uniform3f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade),\n 'u_opacity': new Uniform1f(context, locations.u_opacity)\n});\n\nconst fillExtrusionUniformValues = (\n matrix: mat4,\n painter: Painter,\n shouldUseVerticalGradient: boolean,\n opacity: number\n): UniformValues => {\n const light = painter.style.light;\n const _lp = light.properties.get('position');\n const lightPos = [_lp.x, _lp.y, _lp.z] as vec3;\n const lightMat = mat3.create();\n if (light.properties.get('anchor') === 'viewport') {\n mat3.fromRotation(lightMat, -painter.transform.angle);\n }\n vec3.transformMat3(lightPos, lightPos, lightMat);\n\n const lightColor = light.properties.get('color');\n\n return {\n 'u_matrix': matrix,\n 'u_lightpos': lightPos,\n 'u_lightintensity': light.properties.get('intensity'),\n 'u_lightcolor': [lightColor.r, lightColor.g, lightColor.b],\n 'u_vertical_gradient': +shouldUseVerticalGradient,\n 'u_opacity': opacity\n };\n};\n\nconst fillExtrusionPatternUniformValues = (\n matrix: mat4,\n painter: Painter,\n shouldUseVerticalGradient: boolean,\n opacity: number,\n coord: OverscaledTileID,\n crossfade: CrossfadeParameters,\n tile: Tile\n): UniformValues => {\n return extend(fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity),\n patternUniformValues(crossfade, painter, tile),\n {\n 'u_height_factor': -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8\n });\n};\n\nexport {\n fillExtrusionUniforms,\n fillExtrusionPatternUniforms,\n fillExtrusionUniformValues,\n fillExtrusionPatternUniformValues\n};\n","import * as glMatrix from \"./common.js\";\n/**\n * 3x3 Matrix\n * @module mat3\n */\n\n/**\n * Creates a new identity mat3\n *\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(9);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n }\n\n out[0] = 1;\n out[4] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the upper-left 3x3 values into the given mat3.\n *\n * @param {mat3} out the receiving 3x3 matrix\n * @param {ReadonlyMat4} a the source 4x4 matrix\n * @returns {mat3} out\n */\n\nexport function fromMat4(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[4];\n out[4] = a[5];\n out[5] = a[6];\n out[6] = a[8];\n out[7] = a[9];\n out[8] = a[10];\n return out;\n}\n/**\n * Creates a new mat3 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat3} a matrix to clone\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Copy the values from one mat3 to another\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Create a new mat3 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} A new mat3\n */\n\nexport function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set the components of a mat3 to the given values\n *\n * @param {mat3} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} out\n */\n\nexport function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set a mat3 to the identity matrix\n *\n * @param {mat3} out the receiving matrix\n * @returns {mat3} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a12 = a[5];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a01;\n out[5] = a[7];\n out[6] = a02;\n out[7] = a12;\n } else {\n out[0] = a[0];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a[1];\n out[4] = a[4];\n out[5] = a[7];\n out[6] = a[2];\n out[7] = a[5];\n out[8] = a[8];\n }\n\n return out;\n}\n/**\n * Inverts a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b01 = a22 * a11 - a12 * a21;\n var b11 = -a22 * a10 + a12 * a20;\n var b21 = a21 * a10 - a11 * a20; // Calculate the determinant\n\n var det = a00 * b01 + a01 * b11 + a02 * b21;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = b01 * det;\n out[1] = (-a22 * a01 + a02 * a21) * det;\n out[2] = (a12 * a01 - a02 * a11) * det;\n out[3] = b11 * det;\n out[4] = (a22 * a00 - a02 * a20) * det;\n out[5] = (-a12 * a00 + a02 * a10) * det;\n out[6] = b21 * det;\n out[7] = (-a21 * a00 + a01 * a20) * det;\n out[8] = (a11 * a00 - a01 * a10) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n out[0] = a11 * a22 - a12 * a21;\n out[1] = a02 * a21 - a01 * a22;\n out[2] = a01 * a12 - a02 * a11;\n out[3] = a12 * a20 - a10 * a22;\n out[4] = a00 * a22 - a02 * a20;\n out[5] = a02 * a10 - a00 * a12;\n out[6] = a10 * a21 - a11 * a20;\n out[7] = a01 * a20 - a00 * a21;\n out[8] = a00 * a11 - a01 * a10;\n return out;\n}\n/**\n * Calculates the determinant of a mat3\n *\n * @param {ReadonlyMat3} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);\n}\n/**\n * Multiplies two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b00 = b[0],\n b01 = b[1],\n b02 = b[2];\n var b10 = b[3],\n b11 = b[4],\n b12 = b[5];\n var b20 = b[6],\n b21 = b[7],\n b22 = b[8];\n out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n return out;\n}\n/**\n * Translate a mat3 by the given vector\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to translate\n * @param {ReadonlyVec2} v vector to translate by\n * @returns {mat3} out\n */\n\nexport function translate(out, a, v) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n x = v[0],\n y = v[1];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a10;\n out[4] = a11;\n out[5] = a12;\n out[6] = x * a00 + y * a10 + a20;\n out[7] = x * a01 + y * a11 + a21;\n out[8] = x * a02 + y * a12 + a22;\n return out;\n}\n/**\n * Rotates a mat3 by the given angle\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function rotate(out, a, rad) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c * a00 + s * a10;\n out[1] = c * a01 + s * a11;\n out[2] = c * a02 + s * a12;\n out[3] = c * a10 - s * a00;\n out[4] = c * a11 - s * a01;\n out[5] = c * a12 - s * a02;\n out[6] = a20;\n out[7] = a21;\n out[8] = a22;\n return out;\n}\n/**\n * Scales the mat3 by the dimensions in the given vec2\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat3} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1];\n out[0] = x * a[0];\n out[1] = x * a[1];\n out[2] = x * a[2];\n out[3] = y * a[3];\n out[4] = y * a[4];\n out[5] = y * a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.translate(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Translation vector\n * @returns {mat3} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = v[0];\n out[7] = v[1];\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.rotate(dest, dest, rad);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = -s;\n out[4] = c;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.scale(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Scaling vector\n * @returns {mat3} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = v[1];\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the values from a mat2d into a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat2d} a the matrix to copy\n * @returns {mat3} out\n **/\n\nexport function fromMat2d(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = 0;\n out[3] = a[2];\n out[4] = a[3];\n out[5] = 0;\n out[6] = a[4];\n out[7] = a[5];\n out[8] = 1;\n return out;\n}\n/**\n * Calculates a 3x3 matrix from the given quaternion\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat3} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[3] = yx - wz;\n out[6] = zx + wy;\n out[1] = yx + wz;\n out[4] = 1 - xx - zz;\n out[7] = zy - wx;\n out[2] = zx - wy;\n out[5] = zy + wx;\n out[8] = 1 - xx - yy;\n return out;\n}\n/**\n * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from\n *\n * @returns {mat3} out\n */\n\nexport function normalFromMat4(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n return out;\n}\n/**\n * Generates a 2D projection matrix with the given bounds\n *\n * @param {mat3} out mat3 frustum matrix will be written into\n * @param {number} width Width of your gl context\n * @param {number} height Height of gl context\n * @returns {mat3} out\n */\n\nexport function projection(out, width, height) {\n out[0] = 2 / width;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = -2 / height;\n out[5] = 0;\n out[6] = -1;\n out[7] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat3\n *\n * @param {ReadonlyMat3} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat3\n *\n * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);\n}\n/**\n * Adds two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat3} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n return out;\n}\n/**\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat3} out the receiving vector\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat3} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3],\n a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7],\n a8 = a[8];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));\n}\n/**\n * Alias for {@link mat3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat3.subtract}\n * @function\n */\n\nexport var sub = subtract;","import {patternUniformValues} from './pattern';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport {extend} from '../../util/util';\n\nimport type {Painter} from '../painter';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {Context} from '../../gl/context';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport type {Tile} from '../../source/tile';\nimport {mat4} from 'gl-matrix';\n\nexport type FillUniformsType = {\n 'u_matrix': UniformMatrix4f;\n};\n\nexport type FillOutlineUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_world': Uniform2f;\n};\n\nexport type FillPatternUniformsType = {\n 'u_matrix': UniformMatrix4f;\n // pattern uniforms:\n 'u_texsize': Uniform2f;\n 'u_image': Uniform1i;\n 'u_pixel_coord_upper': Uniform2f;\n 'u_pixel_coord_lower': Uniform2f;\n 'u_scale': Uniform3f;\n 'u_fade': Uniform1f;\n};\n\nexport type FillOutlinePatternUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_world': Uniform2f;\n // pattern uniforms:\n 'u_texsize': Uniform2f;\n 'u_image': Uniform1i;\n 'u_pixel_coord_upper': Uniform2f;\n 'u_pixel_coord_lower': Uniform2f;\n 'u_scale': Uniform3f;\n 'u_fade': Uniform1f;\n};\n\nconst fillUniforms = (context: Context, locations: UniformLocations): FillUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix)\n});\n\nconst fillPatternUniforms = (context: Context, locations: UniformLocations): FillPatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n 'u_scale': new Uniform3f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade)\n});\n\nconst fillOutlineUniforms = (context: Context, locations: UniformLocations): FillOutlineUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_world': new Uniform2f(context, locations.u_world)\n});\n\nconst fillOutlinePatternUniforms = (context: Context, locations: UniformLocations): FillOutlinePatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_world': new Uniform2f(context, locations.u_world),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n 'u_scale': new Uniform3f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade)\n});\n\nconst fillUniformValues = (matrix: mat4): UniformValues => ({\n 'u_matrix': matrix\n});\n\nconst fillPatternUniformValues = (\n matrix: mat4,\n painter: Painter,\n crossfade: CrossfadeParameters,\n tile: Tile\n): UniformValues => extend(\n fillUniformValues(matrix),\n patternUniformValues(crossfade, painter, tile)\n);\n\nconst fillOutlineUniformValues = (matrix: mat4, drawingBufferSize: [number, number]): UniformValues => ({\n 'u_matrix': matrix,\n 'u_world': drawingBufferSize\n});\n\nconst fillOutlinePatternUniformValues = (\n matrix: mat4,\n painter: Painter,\n crossfade: CrossfadeParameters,\n tile: Tile,\n drawingBufferSize: [number, number]\n): UniformValues => extend(\n fillPatternUniformValues(matrix, painter, crossfade, tile),\n {\n 'u_world': drawingBufferSize\n }\n);\n\nexport {\n fillUniforms,\n fillPatternUniforms,\n fillOutlineUniforms,\n fillOutlinePatternUniforms,\n fillUniformValues,\n fillPatternUniformValues,\n fillOutlineUniformValues,\n fillOutlinePatternUniformValues\n};\n","import {Uniform1i, Uniform1f, Uniform2f, UniformMatrix4f} from '../uniform_binding';\nimport {pixelsToTileUnits} from '../../source/pixels_to_tile_units';\n\nimport type {Context} from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {OverscaledTileID} from '../../source/tile_id';\nimport type {Tile} from '../../source/tile';\nimport type {CircleStyleLayer} from '../../style/style_layer/circle_style_layer';\nimport type {Painter} from '../painter';\n\nexport type CircleUniformsType = {\n 'u_camera_to_center_distance': Uniform1f;\n 'u_scale_with_map': Uniform1i;\n 'u_pitch_with_map': Uniform1i;\n 'u_extrude_scale': Uniform2f;\n 'u_device_pixel_ratio': Uniform1f;\n 'u_matrix': UniformMatrix4f;\n};\n\nconst circleUniforms = (context: Context, locations: UniformLocations): CircleUniformsType => ({\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_scale_with_map': new Uniform1i(context, locations.u_scale_with_map),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n 'u_extrude_scale': new Uniform2f(context, locations.u_extrude_scale),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix)\n});\n\nconst circleUniformValues = (\n painter: Painter,\n coord: OverscaledTileID,\n tile: Tile,\n layer: CircleStyleLayer\n): UniformValues => {\n const transform = painter.transform;\n\n let pitchWithMap: boolean, extrudeScale: [number, number];\n if (layer.paint.get('circle-pitch-alignment') === 'map') {\n const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom);\n pitchWithMap = true;\n extrudeScale = [pixelRatio, pixelRatio];\n } else {\n pitchWithMap = false;\n extrudeScale = transform.pixelsToGLUnits;\n }\n\n return {\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\n 'u_scale_with_map': +(layer.paint.get('circle-pitch-scale') === 'map'),\n 'u_matrix': painter.translatePosMatrix(\n coord.posMatrix,\n tile,\n layer.paint.get('circle-translate'),\n layer.paint.get('circle-translate-anchor')),\n 'u_pitch_with_map': +(pitchWithMap),\n 'u_device_pixel_ratio': painter.pixelRatio,\n 'u_extrude_scale': extrudeScale\n };\n};\n\nexport {circleUniforms, circleUniformValues};\n","import {Uniform1f, Uniform2f, UniformMatrix4f} from '../uniform_binding';\nimport type {Context} from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {Transform} from '../../geo/transform';\nimport {mat4} from 'gl-matrix';\n\nexport type CollisionUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_pixel_extrude_scale': Uniform2f;\n};\n\nexport type CollisionCircleUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_inv_matrix': UniformMatrix4f;\n 'u_camera_to_center_distance': Uniform1f;\n 'u_viewport_size': Uniform2f;\n};\n\nconst collisionUniforms = (context: Context, locations: UniformLocations): CollisionUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_pixel_extrude_scale': new Uniform2f(context, locations.u_pixel_extrude_scale)\n});\n\nconst collisionCircleUniforms = (context: Context, locations: UniformLocations): CollisionCircleUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_inv_matrix': new UniformMatrix4f(context, locations.u_inv_matrix),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_viewport_size': new Uniform2f(context, locations.u_viewport_size)\n});\n\nconst collisionUniformValues = (transform: {width: number; height: number}, matrix: mat4): UniformValues => {\n return {\n 'u_matrix': matrix,\n 'u_pixel_extrude_scale': [1.0 / transform.width, 1.0 / transform.height],\n };\n};\n\nconst collisionCircleUniformValues = (matrix: mat4, invMatrix: mat4, transform: Transform): UniformValues => {\n return {\n 'u_matrix': matrix,\n 'u_inv_matrix': invMatrix,\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\n 'u_viewport_size': [transform.width, transform.height]\n };\n};\n\nexport {collisionUniforms, collisionUniformValues, collisionCircleUniforms, collisionCircleUniformValues};\n","import {UniformColor, UniformMatrix4f, Uniform1i, Uniform1f} from '../uniform_binding';\n\nimport type {Context} from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {mat4} from 'gl-matrix';\n\nexport type DebugUniformsType = {\n 'u_color': UniformColor;\n 'u_matrix': UniformMatrix4f;\n 'u_overlay': Uniform1i;\n 'u_overlay_scale': Uniform1f;\n};\n\nconst debugUniforms = (context: Context, locations: UniformLocations): DebugUniformsType => ({\n 'u_color': new UniformColor(context, locations.u_color),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_overlay': new Uniform1i(context, locations.u_overlay),\n 'u_overlay_scale': new Uniform1f(context, locations.u_overlay_scale)\n});\n\nconst debugUniformValues = (matrix: mat4, color: Color, scaleRatio: number = 1): UniformValues => ({\n 'u_matrix': matrix,\n 'u_color': color,\n 'u_overlay': 0,\n 'u_overlay_scale': scaleRatio\n});\n\nexport {debugUniforms, debugUniformValues};\n","import {UniformMatrix4f} from '../uniform_binding';\n\nimport type {Context} from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport {mat4} from 'gl-matrix';\n\nexport type ClippingMaskUniformsType = {\n 'u_matrix': UniformMatrix4f;\n};\n\nconst clippingMaskUniforms = (context: Context, locations: UniformLocations): ClippingMaskUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix)\n});\n\nconst clippingMaskUniformValues = (matrix: mat4): UniformValues => ({\n 'u_matrix': matrix\n});\n\nexport {clippingMaskUniforms, clippingMaskUniformValues};\n","import {mat4} from 'gl-matrix';\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport {pixelsToTileUnits} from '../../source/pixels_to_tile_units';\n\nimport type {Context} from '../../gl/context';\nimport type {Tile} from '../../source/tile';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {Painter} from '../painter';\nimport type {HeatmapStyleLayer} from '../../style/style_layer/heatmap_style_layer';\n\nexport type HeatmapUniformsType = {\n 'u_extrude_scale': Uniform1f;\n 'u_intensity': Uniform1f;\n 'u_matrix': UniformMatrix4f;\n};\n\nexport type HeatmapTextureUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_world': Uniform2f;\n 'u_image': Uniform1i;\n 'u_color_ramp': Uniform1i;\n 'u_opacity': Uniform1f;\n};\n\nconst heatmapUniforms = (context: Context, locations: UniformLocations): HeatmapUniformsType => ({\n 'u_extrude_scale': new Uniform1f(context, locations.u_extrude_scale),\n 'u_intensity': new Uniform1f(context, locations.u_intensity),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix)\n});\n\nconst heatmapTextureUniforms = (context: Context, locations: UniformLocations): HeatmapTextureUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_world': new Uniform2f(context, locations.u_world),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_color_ramp': new Uniform1i(context, locations.u_color_ramp),\n 'u_opacity': new Uniform1f(context, locations.u_opacity)\n});\n\nconst heatmapUniformValues = (matrix: mat4, tile: Tile, zoom: number, intensity: number): UniformValues => ({\n 'u_matrix': matrix,\n 'u_extrude_scale': pixelsToTileUnits(tile, 1, zoom),\n 'u_intensity': intensity\n});\n\nconst heatmapTextureUniformValues = (\n painter: Painter,\n layer: HeatmapStyleLayer,\n textureUnit: number,\n colorRampUnit: number\n): UniformValues => {\n const matrix = mat4.create();\n mat4.ortho(matrix, 0, painter.width, painter.height, 0, 0, 1);\n\n const gl = painter.context.gl;\n\n return {\n 'u_matrix': matrix,\n 'u_world': [gl.drawingBufferWidth, gl.drawingBufferHeight],\n 'u_image': textureUnit,\n 'u_color_ramp': colorRampUnit,\n 'u_opacity': layer.paint.get('heatmap-opacity')\n };\n};\n\nexport {\n heatmapUniforms,\n heatmapTextureUniforms,\n heatmapUniformValues,\n heatmapTextureUniformValues\n};\n","import {mat4} from 'gl-matrix';\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformColor,\n UniformMatrix4f,\n Uniform4f\n} from '../uniform_binding';\nimport {EXTENT} from '../../data/extent';\nimport {MercatorCoordinate} from '../../geo/mercator_coordinate';\n\nimport type {Context} from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {Tile} from '../../source/tile';\nimport type {Painter} from '../painter';\nimport type {HillshadeStyleLayer} from '../../style/style_layer/hillshade_style_layer';\nimport type {DEMData} from '../../data/dem_data';\nimport type {OverscaledTileID} from '../../source/tile_id';\n\nexport type HillshadeUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_image': Uniform1i;\n 'u_latrange': Uniform2f;\n 'u_light': Uniform2f;\n 'u_shadow': UniformColor;\n 'u_highlight': UniformColor;\n 'u_accent': UniformColor;\n};\n\nexport type HillshadePrepareUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_image': Uniform1i;\n 'u_dimension': Uniform2f;\n 'u_zoom': Uniform1f;\n 'u_unpack': Uniform4f;\n};\n\nconst hillshadeUniforms = (context: Context, locations: UniformLocations): HillshadeUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_latrange': new Uniform2f(context, locations.u_latrange),\n 'u_light': new Uniform2f(context, locations.u_light),\n 'u_shadow': new UniformColor(context, locations.u_shadow),\n 'u_highlight': new UniformColor(context, locations.u_highlight),\n 'u_accent': new UniformColor(context, locations.u_accent)\n});\n\nconst hillshadePrepareUniforms = (context: Context, locations: UniformLocations): HillshadePrepareUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_dimension': new Uniform2f(context, locations.u_dimension),\n 'u_zoom': new Uniform1f(context, locations.u_zoom),\n 'u_unpack': new Uniform4f(context, locations.u_unpack)\n});\n\nconst hillshadeUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: HillshadeStyleLayer,\n coord: OverscaledTileID\n): UniformValues => {\n const shadow = layer.paint.get('hillshade-shadow-color');\n const highlight = layer.paint.get('hillshade-highlight-color');\n const accent = layer.paint.get('hillshade-accent-color');\n\n let azimuthal = layer.paint.get('hillshade-illumination-direction') * (Math.PI / 180);\n // modify azimuthal angle by map rotation if light is anchored at the viewport\n if (layer.paint.get('hillshade-illumination-anchor') === 'viewport') {\n azimuthal -= painter.transform.angle;\n }\n const align = !painter.options.moving;\n return {\n 'u_matrix': coord ? coord.posMatrix : painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped(), align),\n 'u_image': 0,\n 'u_latrange': getTileLatRange(painter, tile.tileID),\n 'u_light': [layer.paint.get('hillshade-exaggeration'), azimuthal],\n 'u_shadow': shadow,\n 'u_highlight': highlight,\n 'u_accent': accent\n };\n};\n\nconst hillshadeUniformPrepareValues = (tileID: OverscaledTileID, dem: DEMData): UniformValues => {\n\n const stride = dem.stride;\n const matrix = mat4.create();\n // Flip rendering at y axis.\n mat4.ortho(matrix, 0, EXTENT, -EXTENT, 0, 0, 1);\n mat4.translate(matrix, matrix, [0, -EXTENT, 0]);\n\n return {\n 'u_matrix': matrix,\n 'u_image': 1,\n 'u_dimension': [stride, stride],\n 'u_zoom': tileID.overscaledZ,\n 'u_unpack': dem.getUnpackVector()\n };\n};\n\nfunction getTileLatRange(painter: Painter, tileID: OverscaledTileID) {\n // for scaling the magnitude of a points slope by its latitude\n const tilesAtZoom = Math.pow(2, tileID.canonical.z);\n const y = tileID.canonical.y;\n return [\n new MercatorCoordinate(0, y / tilesAtZoom).toLngLat().lat,\n new MercatorCoordinate(0, (y + 1) / tilesAtZoom).toLngLat().lat];\n}\n\nexport {\n hillshadeUniforms,\n hillshadePrepareUniforms,\n hillshadeUniformValues,\n hillshadeUniformPrepareValues\n};\n","import {Uniform1i, Uniform1f, Uniform2f, Uniform3f, UniformMatrix4f} from '../uniform_binding';\nimport {pixelsToTileUnits} from '../../source/pixels_to_tile_units';\nimport {extend} from '../../util/util';\n\nimport type {Context} from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {Transform} from '../../geo/transform';\nimport type {Tile} from '../../source/tile';\nimport type {CrossFaded} from '../../style/properties';\nimport type {LineStyleLayer} from '../../style/style_layer/line_style_layer';\nimport type {Painter} from '../painter';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport {OverscaledTileID} from '../../source/tile_id';\n\nexport type LineUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_ratio': Uniform1f;\n 'u_device_pixel_ratio': Uniform1f;\n 'u_units_to_pixels': Uniform2f;\n};\n\nexport type LineGradientUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_ratio': Uniform1f;\n 'u_device_pixel_ratio': Uniform1f;\n 'u_units_to_pixels': Uniform2f;\n 'u_image': Uniform1i;\n 'u_image_height': Uniform1f;\n};\n\nexport type LinePatternUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_texsize': Uniform2f;\n 'u_ratio': Uniform1f;\n 'u_device_pixel_ratio': Uniform1f;\n 'u_units_to_pixels': Uniform2f;\n 'u_image': Uniform1i;\n 'u_scale': Uniform3f;\n 'u_fade': Uniform1f;\n};\n\nexport type LineSDFUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_ratio': Uniform1f;\n 'u_device_pixel_ratio': Uniform1f;\n 'u_units_to_pixels': Uniform2f;\n 'u_patternscale_a': Uniform2f;\n 'u_patternscale_b': Uniform2f;\n 'u_sdfgamma': Uniform1f;\n 'u_image': Uniform1i;\n 'u_tex_y_a': Uniform1f;\n 'u_tex_y_b': Uniform1f;\n 'u_mix': Uniform1f;\n};\n\nconst lineUniforms = (context: Context, locations: UniformLocations): LineUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_ratio': new Uniform1f(context, locations.u_ratio),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels)\n});\n\nconst lineGradientUniforms = (context: Context, locations: UniformLocations): LineGradientUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_ratio': new Uniform1f(context, locations.u_ratio),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_image_height': new Uniform1f(context, locations.u_image_height)\n});\n\nconst linePatternUniforms = (context: Context, locations: UniformLocations): LinePatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_ratio': new Uniform1f(context, locations.u_ratio),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels),\n 'u_scale': new Uniform3f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade)\n});\n\nconst lineSDFUniforms = (context: Context, locations: UniformLocations): LineSDFUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_ratio': new Uniform1f(context, locations.u_ratio),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels),\n 'u_patternscale_a': new Uniform2f(context, locations.u_patternscale_a),\n 'u_patternscale_b': new Uniform2f(context, locations.u_patternscale_b),\n 'u_sdfgamma': new Uniform1f(context, locations.u_sdfgamma),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_tex_y_a': new Uniform1f(context, locations.u_tex_y_a),\n 'u_tex_y_b': new Uniform1f(context, locations.u_tex_y_b),\n 'u_mix': new Uniform1f(context, locations.u_mix)\n});\n\nconst lineUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: LineStyleLayer,\n coord: OverscaledTileID\n): UniformValues => {\n const transform = painter.transform;\n\n return {\n 'u_matrix': calculateMatrix(painter, tile, layer, coord),\n 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom),\n 'u_device_pixel_ratio': painter.pixelRatio,\n 'u_units_to_pixels': [\n 1 / transform.pixelsToGLUnits[0],\n 1 / transform.pixelsToGLUnits[1]\n ]\n };\n};\n\nconst lineGradientUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: LineStyleLayer,\n imageHeight: number,\n coord: OverscaledTileID\n): UniformValues => {\n return extend(lineUniformValues(painter, tile, layer, coord), {\n 'u_image': 0,\n 'u_image_height': imageHeight,\n });\n};\n\nconst linePatternUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: LineStyleLayer,\n crossfade: CrossfadeParameters,\n coord: OverscaledTileID\n): UniformValues => {\n const transform = painter.transform;\n const tileZoomRatio = calculateTileRatio(tile, transform);\n return {\n 'u_matrix': calculateMatrix(painter, tile, layer, coord),\n 'u_texsize': tile.imageAtlasTexture.size,\n // camera zoom ratio\n 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom),\n 'u_device_pixel_ratio': painter.pixelRatio,\n 'u_image': 0,\n 'u_scale': [tileZoomRatio, crossfade.fromScale, crossfade.toScale],\n 'u_fade': crossfade.t,\n 'u_units_to_pixels': [\n 1 / transform.pixelsToGLUnits[0],\n 1 / transform.pixelsToGLUnits[1]\n ]\n };\n};\n\nconst lineSDFUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: LineStyleLayer,\n dasharray: CrossFaded>,\n crossfade: CrossfadeParameters,\n coord: OverscaledTileID\n): UniformValues => {\n const transform = painter.transform;\n const lineAtlas = painter.lineAtlas;\n const tileRatio = calculateTileRatio(tile, transform);\n\n const round = layer.layout.get('line-cap') === 'round';\n\n const posA = lineAtlas.getDash(dasharray.from, round);\n const posB = lineAtlas.getDash(dasharray.to, round);\n\n const widthA = posA.width * crossfade.fromScale;\n const widthB = posB.width * crossfade.toScale;\n\n return extend(lineUniformValues(painter, tile, layer, coord), {\n 'u_patternscale_a': [tileRatio / widthA, -posA.height / 2],\n 'u_patternscale_b': [tileRatio / widthB, -posB.height / 2],\n 'u_sdfgamma': lineAtlas.width / (Math.min(widthA, widthB) * 256 * painter.pixelRatio) / 2,\n 'u_image': 0,\n 'u_tex_y_a': posA.y,\n 'u_tex_y_b': posB.y,\n 'u_mix': crossfade.t\n });\n};\n\nfunction calculateTileRatio(tile: Tile, transform: Transform) {\n return 1 / pixelsToTileUnits(tile, 1, transform.tileZoom);\n}\n\nfunction calculateMatrix(painter: Painter, tile: Tile, layer: LineStyleLayer, coord: OverscaledTileID) {\n return painter.translatePosMatrix(\n coord ? coord.posMatrix : tile.tileID.posMatrix,\n tile,\n layer.paint.get('line-translate'),\n layer.paint.get('line-translate-anchor')\n );\n}\n\nexport {\n lineUniforms,\n lineGradientUniforms,\n linePatternUniforms,\n lineSDFUniforms,\n lineUniformValues,\n lineGradientUniformValues,\n linePatternUniformValues,\n lineSDFUniformValues\n};\n","import {Uniform1i, Uniform1f, Uniform2f, Uniform3f, UniformMatrix4f} from '../uniform_binding';\n\nimport type {Context} from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {RasterStyleLayer} from '../../style/style_layer/raster_style_layer';\nimport {mat4} from 'gl-matrix';\n\nexport type RasterUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_tl_parent': Uniform2f;\n 'u_scale_parent': Uniform1f;\n 'u_buffer_scale': Uniform1f;\n 'u_fade_t': Uniform1f;\n 'u_opacity': Uniform1f;\n 'u_image0': Uniform1i;\n 'u_image1': Uniform1i;\n 'u_brightness_low': Uniform1f;\n 'u_brightness_high': Uniform1f;\n 'u_saturation_factor': Uniform1f;\n 'u_contrast_factor': Uniform1f;\n 'u_spin_weights': Uniform3f;\n};\n\nconst rasterUniforms = (context: Context, locations: UniformLocations): RasterUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_tl_parent': new Uniform2f(context, locations.u_tl_parent),\n 'u_scale_parent': new Uniform1f(context, locations.u_scale_parent),\n 'u_buffer_scale': new Uniform1f(context, locations.u_buffer_scale),\n 'u_fade_t': new Uniform1f(context, locations.u_fade_t),\n 'u_opacity': new Uniform1f(context, locations.u_opacity),\n 'u_image0': new Uniform1i(context, locations.u_image0),\n 'u_image1': new Uniform1i(context, locations.u_image1),\n 'u_brightness_low': new Uniform1f(context, locations.u_brightness_low),\n 'u_brightness_high': new Uniform1f(context, locations.u_brightness_high),\n 'u_saturation_factor': new Uniform1f(context, locations.u_saturation_factor),\n 'u_contrast_factor': new Uniform1f(context, locations.u_contrast_factor),\n 'u_spin_weights': new Uniform3f(context, locations.u_spin_weights)\n});\n\nconst rasterUniformValues = (\n matrix: mat4,\n parentTL: [number, number],\n parentScaleBy: number,\n fade: {\n mix: number;\n opacity: number;\n },\n layer: RasterStyleLayer\n): UniformValues => ({\n 'u_matrix': matrix,\n 'u_tl_parent': parentTL,\n 'u_scale_parent': parentScaleBy,\n 'u_buffer_scale': 1,\n 'u_fade_t': fade.mix,\n 'u_opacity': fade.opacity * layer.paint.get('raster-opacity'),\n 'u_image0': 0,\n 'u_image1': 1,\n 'u_brightness_low': layer.paint.get('raster-brightness-min'),\n 'u_brightness_high': layer.paint.get('raster-brightness-max'),\n 'u_saturation_factor': saturationFactor(layer.paint.get('raster-saturation')),\n 'u_contrast_factor': contrastFactor(layer.paint.get('raster-contrast')),\n 'u_spin_weights': spinWeights(layer.paint.get('raster-hue-rotate'))\n});\n\nfunction spinWeights(angle) {\n angle *= Math.PI / 180;\n const s = Math.sin(angle);\n const c = Math.cos(angle);\n return [\n (2 * c + 1) / 3,\n (-Math.sqrt(3) * s - c + 1) / 3,\n (Math.sqrt(3) * s - c + 1) / 3\n ];\n}\n\nfunction contrastFactor(contrast) {\n return contrast > 0 ?\n 1 / (1 - contrast) :\n 1 + contrast;\n}\n\nfunction saturationFactor(saturation) {\n return saturation > 0 ?\n 1 - 1 / (1.001 - saturation) :\n -saturation;\n}\n\nexport {rasterUniforms, rasterUniformValues};\n","import {Uniform1i, Uniform1f, Uniform2f, UniformMatrix4f} from '../uniform_binding';\nimport {extend} from '../../util/util';\n\nimport type {Context} from '../../gl/context';\nimport type {Painter} from '../painter';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport {mat4} from 'gl-matrix';\n\nexport type SymbolIconUniformsType = {\n 'u_is_size_zoom_constant': Uniform1i;\n 'u_is_size_feature_constant': Uniform1i;\n 'u_size_t': Uniform1f;\n 'u_size': Uniform1f;\n 'u_camera_to_center_distance': Uniform1f;\n 'u_pitch': Uniform1f;\n 'u_rotate_symbol': Uniform1i;\n 'u_aspect_ratio': Uniform1f;\n 'u_fade_change': Uniform1f;\n 'u_matrix': UniformMatrix4f;\n 'u_label_plane_matrix': UniformMatrix4f;\n 'u_coord_matrix': UniformMatrix4f;\n 'u_is_text': Uniform1i;\n 'u_pitch_with_map': Uniform1i;\n 'u_is_along_line': Uniform1i;\n 'u_is_variable_anchor': Uniform1i;\n 'u_texsize': Uniform2f;\n 'u_texture': Uniform1i;\n 'u_translation': Uniform2f;\n 'u_pitched_scale': Uniform1f;\n};\n\nexport type SymbolSDFUniformsType = {\n 'u_is_size_zoom_constant': Uniform1i;\n 'u_is_size_feature_constant': Uniform1i;\n 'u_size_t': Uniform1f;\n 'u_size': Uniform1f;\n 'u_camera_to_center_distance': Uniform1f;\n 'u_pitch': Uniform1f;\n 'u_rotate_symbol': Uniform1i;\n 'u_aspect_ratio': Uniform1f;\n 'u_fade_change': Uniform1f;\n 'u_matrix': UniformMatrix4f;\n 'u_label_plane_matrix': UniformMatrix4f;\n 'u_coord_matrix': UniformMatrix4f;\n 'u_is_text': Uniform1i;\n 'u_pitch_with_map': Uniform1i;\n 'u_is_along_line': Uniform1i;\n 'u_is_variable_anchor': Uniform1i;\n 'u_texsize': Uniform2f;\n 'u_texture': Uniform1i;\n 'u_gamma_scale': Uniform1f;\n 'u_device_pixel_ratio': Uniform1f;\n 'u_is_halo': Uniform1i;\n 'u_translation': Uniform2f;\n 'u_pitched_scale': Uniform1f;\n};\n\nexport type symbolTextAndIconUniformsType = {\n 'u_is_size_zoom_constant': Uniform1i;\n 'u_is_size_feature_constant': Uniform1i;\n 'u_size_t': Uniform1f;\n 'u_size': Uniform1f;\n 'u_camera_to_center_distance': Uniform1f;\n 'u_pitch': Uniform1f;\n 'u_rotate_symbol': Uniform1i;\n 'u_aspect_ratio': Uniform1f;\n 'u_fade_change': Uniform1f;\n 'u_matrix': UniformMatrix4f;\n 'u_label_plane_matrix': UniformMatrix4f;\n 'u_coord_matrix': UniformMatrix4f;\n 'u_is_text': Uniform1i;\n 'u_pitch_with_map': Uniform1i;\n 'u_is_along_line': Uniform1i;\n 'u_is_variable_anchor': Uniform1i;\n 'u_texsize': Uniform2f;\n 'u_texsize_icon': Uniform2f;\n 'u_texture': Uniform1i;\n 'u_texture_icon': Uniform1i;\n 'u_gamma_scale': Uniform1f;\n 'u_device_pixel_ratio': Uniform1f;\n 'u_is_halo': Uniform1i;\n 'u_translation': Uniform2f;\n 'u_pitched_scale': Uniform1f;\n};\n\nconst symbolIconUniforms = (context: Context, locations: UniformLocations): SymbolIconUniformsType => ({\n 'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant),\n 'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant),\n 'u_size_t': new Uniform1f(context, locations.u_size_t),\n 'u_size': new Uniform1f(context, locations.u_size),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_pitch': new Uniform1f(context, locations.u_pitch),\n 'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol),\n 'u_aspect_ratio': new Uniform1f(context, locations.u_aspect_ratio),\n 'u_fade_change': new Uniform1f(context, locations.u_fade_change),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix),\n 'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix),\n 'u_is_text': new Uniform1i(context, locations.u_is_text),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n 'u_is_along_line': new Uniform1i(context, locations.u_is_along_line),\n 'u_is_variable_anchor': new Uniform1i(context, locations.u_is_variable_anchor),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_texture': new Uniform1i(context, locations.u_texture),\n 'u_translation': new Uniform2f(context, locations.u_translation),\n 'u_pitched_scale': new Uniform1f(context, locations.u_pitched_scale),\n});\n\nconst symbolSDFUniforms = (context: Context, locations: UniformLocations): SymbolSDFUniformsType => ({\n 'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant),\n 'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant),\n 'u_size_t': new Uniform1f(context, locations.u_size_t),\n 'u_size': new Uniform1f(context, locations.u_size),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_pitch': new Uniform1f(context, locations.u_pitch),\n 'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol),\n 'u_aspect_ratio': new Uniform1f(context, locations.u_aspect_ratio),\n 'u_fade_change': new Uniform1f(context, locations.u_fade_change),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix),\n 'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix),\n 'u_is_text': new Uniform1i(context, locations.u_is_text),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n 'u_is_along_line': new Uniform1i(context, locations.u_is_along_line),\n 'u_is_variable_anchor': new Uniform1i(context, locations.u_is_variable_anchor),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_texture': new Uniform1i(context, locations.u_texture),\n 'u_gamma_scale': new Uniform1f(context, locations.u_gamma_scale),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_is_halo': new Uniform1i(context, locations.u_is_halo),\n 'u_translation': new Uniform2f(context, locations.u_translation),\n 'u_pitched_scale': new Uniform1f(context, locations.u_pitched_scale),\n});\n\nconst symbolTextAndIconUniforms = (context: Context, locations: UniformLocations): symbolTextAndIconUniformsType => ({\n 'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant),\n 'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant),\n 'u_size_t': new Uniform1f(context, locations.u_size_t),\n 'u_size': new Uniform1f(context, locations.u_size),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_pitch': new Uniform1f(context, locations.u_pitch),\n 'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol),\n 'u_aspect_ratio': new Uniform1f(context, locations.u_aspect_ratio),\n 'u_fade_change': new Uniform1f(context, locations.u_fade_change),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix),\n 'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix),\n 'u_is_text': new Uniform1i(context, locations.u_is_text),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n 'u_is_along_line': new Uniform1i(context, locations.u_is_along_line),\n 'u_is_variable_anchor': new Uniform1i(context, locations.u_is_variable_anchor),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_texsize_icon': new Uniform2f(context, locations.u_texsize_icon),\n 'u_texture': new Uniform1i(context, locations.u_texture),\n 'u_texture_icon': new Uniform1i(context, locations.u_texture_icon),\n 'u_gamma_scale': new Uniform1f(context, locations.u_gamma_scale),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_is_halo': new Uniform1i(context, locations.u_is_halo),\n 'u_translation': new Uniform2f(context, locations.u_translation),\n 'u_pitched_scale': new Uniform1f(context, locations.u_pitched_scale),\n});\n\nconst symbolIconUniformValues = (\n functionType: string,\n size: {\n uSizeT: number;\n uSize: number;\n },\n rotateInShader: boolean,\n pitchWithMap: boolean,\n isAlongLine: boolean,\n isVariableAnchor: boolean,\n painter: Painter,\n matrix: mat4,\n labelPlaneMatrix: mat4,\n glCoordMatrix: mat4,\n translation: [number, number],\n isText: boolean,\n texSize: [number, number],\n pitchedScale: number\n): UniformValues => {\n const transform = painter.transform;\n\n return {\n 'u_is_size_zoom_constant': +(functionType === 'constant' || functionType === 'source'),\n 'u_is_size_feature_constant': +(functionType === 'constant' || functionType === 'camera'),\n 'u_size_t': size ? size.uSizeT : 0,\n 'u_size': size ? size.uSize : 0,\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\n 'u_pitch': transform.pitch / 360 * 2 * Math.PI,\n 'u_rotate_symbol': +rotateInShader,\n 'u_aspect_ratio': transform.width / transform.height,\n 'u_fade_change': painter.options.fadeDuration ? painter.symbolFadeChange : 1,\n 'u_matrix': matrix,\n 'u_label_plane_matrix': labelPlaneMatrix,\n 'u_coord_matrix': glCoordMatrix,\n 'u_is_text': +isText,\n 'u_pitch_with_map': +pitchWithMap,\n 'u_is_along_line': isAlongLine,\n 'u_is_variable_anchor': isVariableAnchor,\n 'u_texsize': texSize,\n 'u_texture': 0,\n 'u_translation': translation,\n 'u_pitched_scale': pitchedScale\n };\n};\n\nconst symbolSDFUniformValues = (\n functionType: string,\n size: {\n uSizeT: number;\n uSize: number;\n },\n rotateInShader: boolean,\n pitchWithMap: boolean,\n isAlongLine: boolean,\n isVariableAnchor: boolean,\n painter: Painter,\n matrix: mat4,\n labelPlaneMatrix: mat4,\n glCoordMatrix: mat4,\n translation: [number, number],\n isText: boolean,\n texSize: [number, number],\n isHalo: boolean,\n pitchedScale: number\n): UniformValues => {\n const transform = painter.transform;\n\n return extend(symbolIconUniformValues(functionType, size,\n rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix,\n glCoordMatrix, translation, isText, texSize, pitchedScale), {\n 'u_gamma_scale': (pitchWithMap ? Math.cos(transform._pitch) * transform.cameraToCenterDistance : 1),\n 'u_device_pixel_ratio': painter.pixelRatio,\n 'u_is_halo': +isHalo\n });\n};\n\nconst symbolTextAndIconUniformValues = (\n functionType: string,\n size: {\n uSizeT: number;\n uSize: number;\n },\n rotateInShader: boolean,\n pitchWithMap: boolean,\n isAlongLine: boolean,\n isVariableAnchor: boolean,\n painter: Painter,\n matrix: mat4,\n labelPlaneMatrix: mat4,\n glCoordMatrix: mat4,\n translation: [number, number],\n texSizeSDF: [number, number],\n texSizeIcon: [number, number],\n pitchedScale: number\n): UniformValues => {\n return extend(symbolSDFUniformValues(functionType, size,\n rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix,\n glCoordMatrix, translation, true, texSizeSDF, true, pitchedScale), {\n 'u_texsize_icon': texSizeIcon,\n 'u_texture_icon': 1\n });\n};\n\nexport {symbolIconUniforms, symbolSDFUniforms, symbolIconUniformValues, symbolSDFUniformValues, symbolTextAndIconUniformValues, symbolTextAndIconUniforms};\n","import {bgPatternUniformValues} from './pattern';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformColor,\n UniformMatrix4f\n} from '../uniform_binding';\nimport {extend} from '../../util/util';\n\nimport type {Painter} from '../painter';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {Context} from '../../gl/context';\nimport type {Color, ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\nimport type {CrossFaded} from '../../style/properties';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport type {OverscaledTileID} from '../../source/tile_id';\nimport {mat4} from 'gl-matrix';\n\nexport type BackgroundUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_opacity': Uniform1f;\n 'u_color': UniformColor;\n};\n\nexport type BackgroundPatternUniformsType = {\n 'u_matrix': UniformMatrix4f;\n 'u_opacity': Uniform1f;\n // pattern uniforms:\n 'u_image': Uniform1i;\n 'u_pattern_tl_a': Uniform2f;\n 'u_pattern_br_a': Uniform2f;\n 'u_pattern_tl_b': Uniform2f;\n 'u_pattern_br_b': Uniform2f;\n 'u_texsize': Uniform2f;\n 'u_mix': Uniform1f;\n 'u_pattern_size_a': Uniform2f;\n 'u_pattern_size_b': Uniform2f;\n 'u_scale_a': Uniform1f;\n 'u_scale_b': Uniform1f;\n 'u_pixel_coord_upper': Uniform2f;\n 'u_pixel_coord_lower': Uniform2f;\n 'u_tile_units_to_pixels': Uniform1f;\n};\n\nconst backgroundUniforms = (context: Context, locations: UniformLocations): BackgroundUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_opacity': new Uniform1f(context, locations.u_opacity),\n 'u_color': new UniformColor(context, locations.u_color)\n});\n\nconst backgroundPatternUniforms = (context: Context, locations: UniformLocations): BackgroundPatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_opacity': new Uniform1f(context, locations.u_opacity),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_pattern_tl_a': new Uniform2f(context, locations.u_pattern_tl_a),\n 'u_pattern_br_a': new Uniform2f(context, locations.u_pattern_br_a),\n 'u_pattern_tl_b': new Uniform2f(context, locations.u_pattern_tl_b),\n 'u_pattern_br_b': new Uniform2f(context, locations.u_pattern_br_b),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_mix': new Uniform1f(context, locations.u_mix),\n 'u_pattern_size_a': new Uniform2f(context, locations.u_pattern_size_a),\n 'u_pattern_size_b': new Uniform2f(context, locations.u_pattern_size_b),\n 'u_scale_a': new Uniform1f(context, locations.u_scale_a),\n 'u_scale_b': new Uniform1f(context, locations.u_scale_b),\n 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n 'u_tile_units_to_pixels': new Uniform1f(context, locations.u_tile_units_to_pixels)\n});\n\nconst backgroundUniformValues = (matrix: mat4, opacity: number, color: Color): UniformValues => ({\n 'u_matrix': matrix,\n 'u_opacity': opacity,\n 'u_color': color\n});\n\nconst backgroundPatternUniformValues = (\n matrix: mat4,\n opacity: number,\n painter: Painter,\n image: CrossFaded,\n tile: {\n tileID: OverscaledTileID;\n tileSize: number;\n },\n crossfade: CrossfadeParameters\n): UniformValues => extend(\n bgPatternUniformValues(image, crossfade, painter, tile),\n {\n 'u_matrix': matrix,\n 'u_opacity': opacity\n }\n);\n\nexport {\n backgroundUniforms,\n backgroundPatternUniforms,\n backgroundUniformValues,\n backgroundPatternUniformValues\n};\n","import {fillExtrusionUniforms, fillExtrusionPatternUniforms} from './fill_extrusion_program';\nimport {fillUniforms, fillPatternUniforms, fillOutlineUniforms, fillOutlinePatternUniforms} from './fill_program';\nimport {circleUniforms} from './circle_program';\nimport {collisionUniforms, collisionCircleUniforms} from './collision_program';\nimport {debugUniforms} from './debug_program';\nimport {clippingMaskUniforms} from './clipping_mask_program';\nimport {heatmapUniforms, heatmapTextureUniforms} from './heatmap_program';\nimport {hillshadeUniforms, hillshadePrepareUniforms} from './hillshade_program';\nimport {lineUniforms, lineGradientUniforms, linePatternUniforms, lineSDFUniforms} from './line_program';\nimport {rasterUniforms} from './raster_program';\nimport {symbolIconUniforms, symbolSDFUniforms, symbolTextAndIconUniforms} from './symbol_program';\nimport {backgroundUniforms, backgroundPatternUniforms} from './background_program';\nimport {terrainUniforms, terrainDepthUniforms, terrainCoordsUniforms} from './terrain_program';\nimport {skyUniforms} from './sky_program';\n\nexport const programUniforms = {\n fillExtrusion: fillExtrusionUniforms,\n fillExtrusionPattern: fillExtrusionPatternUniforms,\n fill: fillUniforms,\n fillPattern: fillPatternUniforms,\n fillOutline: fillOutlineUniforms,\n fillOutlinePattern: fillOutlinePatternUniforms,\n circle: circleUniforms,\n collisionBox: collisionUniforms,\n collisionCircle: collisionCircleUniforms,\n debug: debugUniforms,\n clippingMask: clippingMaskUniforms,\n heatmap: heatmapUniforms,\n heatmapTexture: heatmapTextureUniforms,\n hillshade: hillshadeUniforms,\n hillshadePrepare: hillshadePrepareUniforms,\n line: lineUniforms,\n lineGradient: lineGradientUniforms,\n linePattern: linePatternUniforms,\n lineSDF: lineSDFUniforms,\n raster: rasterUniforms,\n symbolIcon: symbolIconUniforms,\n symbolSDF: symbolSDFUniforms,\n symbolTextAndIcon: symbolTextAndIconUniforms,\n background: backgroundUniforms,\n backgroundPattern: backgroundPatternUniforms,\n terrain: terrainUniforms,\n terrainDepth: terrainDepthUniforms,\n terrainCoords: terrainCoordsUniforms,\n sky: skyUniforms\n};\n","import {UniformColor, Uniform1f} from '../uniform_binding';\nimport type {Context} from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport {Transform} from '../../geo/transform';\nimport {Sky} from '../../style/sky';\n\nexport type SkyUniformsType = {\n 'u_sky_color': UniformColor;\n 'u_horizon_color': UniformColor;\n 'u_horizon': Uniform1f;\n 'u_sky_horizon_blend': Uniform1f;\n};\n\nconst skyUniforms = (context: Context, locations: UniformLocations): SkyUniformsType => ({\n 'u_sky_color': new UniformColor(context, locations.u_sky_color),\n 'u_horizon_color': new UniformColor(context, locations.u_horizon_color),\n 'u_horizon': new Uniform1f(context, locations.u_horizon),\n 'u_sky_horizon_blend': new Uniform1f(context, locations.u_sky_horizon_blend),\n});\n\nconst skyUniformValues = (sky: Sky, transform: Transform, pixelRatio: number): UniformValues => ({\n 'u_sky_color': sky.properties.get('sky-color'),\n 'u_horizon_color': sky.properties.get('horizon-color'),\n 'u_horizon': (transform.height / 2 + transform.getHorizon()) * pixelRatio,\n 'u_sky_horizon_blend': (sky.properties.get('sky-horizon-blend') * transform.height / 2) * pixelRatio,\n});\n\nexport {skyUniforms, skyUniformValues};\n","\nimport type {StructArray} from '../util/struct_array';\nimport type {TriangleIndexArray, LineIndexArray, LineStripIndexArray} from '../data/index_array_type';\nimport type {Context} from '../gl/context';\n\n/**\n * @internal\n * an index buffer class\n */\nexport class IndexBuffer {\n context: Context;\n buffer: WebGLBuffer;\n dynamicDraw: boolean;\n\n constructor(context: Context, array: TriangleIndexArray | LineIndexArray | LineStripIndexArray, dynamicDraw?: boolean) {\n this.context = context;\n const gl = context.gl;\n this.buffer = gl.createBuffer();\n this.dynamicDraw = Boolean(dynamicDraw);\n\n // The bound index buffer is part of vertex array object state. We don't want to\n // modify whatever VAO happens to be currently bound, so make sure the default\n // vertex array provided by the context is bound instead.\n this.context.unbindVAO();\n\n context.bindElementBuffer.set(this.buffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);\n\n if (!this.dynamicDraw) {\n delete array.arrayBuffer;\n }\n }\n\n bind() {\n this.context.bindElementBuffer.set(this.buffer);\n }\n\n updateData(array: StructArray) {\n const gl = this.context.gl;\n if (!this.dynamicDraw) throw new Error('Attempted to update data while not in dynamic mode.');\n // The right VAO will get this buffer re-bound later in VertexArrayObject#bind\n // See https://github.com/mapbox/mapbox-gl-js/issues/5620\n this.context.unbindVAO();\n this.bind();\n gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer);\n }\n\n destroy() {\n const gl = this.context.gl;\n if (this.buffer) {\n gl.deleteBuffer(this.buffer);\n delete this.buffer;\n }\n }\n}\n","\nimport type {\n StructArray,\n StructArrayMember\n} from '../util/struct_array';\n\nimport type {Program} from '../render/program';\nimport type {Context} from '../gl/context';\n\n/**\n * An Enum for AttributeType\n */\nconst AttributeType = {\n Int8: 'BYTE',\n Uint8: 'UNSIGNED_BYTE',\n Int16: 'SHORT',\n Uint16: 'UNSIGNED_SHORT',\n Int32: 'INT',\n Uint32: 'UNSIGNED_INT',\n Float32: 'FLOAT'\n};\n\n/**\n * @internal\n * The `VertexBuffer` class turns a `StructArray` into a WebGL buffer. Each member of the StructArray's\n * Struct type is converted to a WebGL attribute.\n */\nexport class VertexBuffer {\n length: number;\n attributes: ReadonlyArray;\n itemSize: number;\n dynamicDraw: boolean;\n context: Context;\n buffer: WebGLBuffer;\n\n /**\n * @param dynamicDraw - Whether this buffer will be repeatedly updated.\n */\n constructor(context: Context, array: StructArray, attributes: ReadonlyArray, dynamicDraw?: boolean) {\n this.length = array.length;\n this.attributes = attributes;\n this.itemSize = array.bytesPerElement;\n this.dynamicDraw = dynamicDraw;\n\n this.context = context;\n const gl = context.gl;\n this.buffer = gl.createBuffer();\n context.bindVertexBuffer.set(this.buffer);\n gl.bufferData(gl.ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);\n\n if (!this.dynamicDraw) {\n delete array.arrayBuffer;\n }\n }\n\n bind() {\n this.context.bindVertexBuffer.set(this.buffer);\n }\n\n updateData(array: StructArray) {\n if (array.length !== this.length) throw new Error(`Length of new data is ${array.length}, which doesn't match current length of ${this.length}`);\n const gl = this.context.gl;\n this.bind();\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, array.arrayBuffer);\n }\n\n enableAttributes(gl: WebGLRenderingContext|WebGL2RenderingContext, program: Program) {\n for (let j = 0; j < this.attributes.length; j++) {\n const member = this.attributes[j];\n const attribIndex: number | void = program.attributes[member.name];\n if (attribIndex !== undefined) {\n gl.enableVertexAttribArray(attribIndex);\n }\n }\n }\n\n /**\n * Set the attribute pointers in a WebGL context\n * @param gl - The WebGL context\n * @param program - The active WebGL program\n * @param vertexOffset - Index of the starting vertex of the segment\n */\n setVertexAttribPointers(gl: WebGLRenderingContext|WebGL2RenderingContext, program: Program, vertexOffset?: number | null) {\n for (let j = 0; j < this.attributes.length; j++) {\n const member = this.attributes[j];\n const attribIndex: number | void = program.attributes[member.name];\n\n if (attribIndex !== undefined) {\n gl.vertexAttribPointer(\n attribIndex,\n member.components,\n (gl as any)[AttributeType[member.type]],\n false,\n this.itemSize,\n member.offset + (this.itemSize * (vertexOffset || 0))\n );\n }\n }\n }\n\n /**\n * Destroy the GL buffer bound to the given WebGL context\n */\n destroy() {\n const gl = this.context.gl;\n if (this.buffer) {\n gl.deleteBuffer(this.buffer);\n delete this.buffer;\n }\n }\n}\n","const cache = new WeakMap();\nexport function isWebGL2(\n gl: WebGLRenderingContext | WebGL2RenderingContext\n): gl is WebGL2RenderingContext {\n if (cache.has(gl)) {\n return cache.get(gl);\n } else {\n const value = gl.getParameter(gl.VERSION)?.startsWith('WebGL 2.0');\n cache.set(gl, value);\n return value;\n }\n}\n","import {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {isWebGL2} from './webgl2';\n\nimport type {Context} from './context';\nimport type {\n BlendFuncType,\n BlendEquationType,\n ColorMaskType,\n DepthRangeType,\n DepthMaskType,\n StencilFuncType,\n StencilOpType,\n DepthFuncType,\n TextureUnitType,\n ViewportType,\n CullFaceModeType,\n FrontFaceType,\n} from './types';\n\nexport interface IValue {\n current: T;\n default: T;\n dirty: boolean;\n get(): T;\n setDefault(): void;\n set(value: T): void;\n}\n\nclass BaseValue implements IValue {\n gl: WebGLRenderingContext|WebGL2RenderingContext;\n current: T;\n default: T;\n dirty: boolean;\n\n constructor(context: Context) {\n this.gl = context.gl;\n this.default = this.getDefault();\n this.current = this.default;\n this.dirty = false;\n }\n\n get(): T {\n return this.current;\n }\n set(value: T) { // eslint-disable-line\n // overridden in child classes;\n }\n\n getDefault(): T {\n return this.default; // overridden in child classes\n }\n setDefault() {\n this.set(this.default);\n }\n}\n\nexport class ClearColor extends BaseValue {\n getDefault(): Color {\n return Color.transparent;\n }\n set(v: Color) {\n const c = this.current;\n if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;\n this.gl.clearColor(v.r, v.g, v.b, v.a);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class ClearDepth extends BaseValue {\n getDefault(): number {\n return 1;\n }\n set(v: number) {\n if (v === this.current && !this.dirty) return;\n this.gl.clearDepth(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class ClearStencil extends BaseValue {\n getDefault(): number {\n return 0;\n }\n set(v: number) {\n if (v === this.current && !this.dirty) return;\n this.gl.clearStencil(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class ColorMask extends BaseValue {\n getDefault(): ColorMaskType {\n return [true, true, true, true];\n }\n set(v: ColorMaskType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;\n this.gl.colorMask(v[0], v[1], v[2], v[3]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthMask extends BaseValue {\n getDefault(): DepthMaskType {\n return true;\n }\n set(v: DepthMaskType): void {\n if (v === this.current && !this.dirty) return;\n this.gl.depthMask(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class StencilMask extends BaseValue {\n getDefault(): number {\n return 0xFF;\n }\n set(v: number): void {\n if (v === this.current && !this.dirty) return;\n this.gl.stencilMask(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class StencilFunc extends BaseValue {\n getDefault(): StencilFuncType {\n return {\n func: this.gl.ALWAYS,\n ref: 0,\n mask: 0xFF\n };\n }\n set(v: StencilFuncType): void {\n const c = this.current;\n if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty) return;\n this.gl.stencilFunc(v.func, v.ref, v.mask);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class StencilOp extends BaseValue {\n getDefault(): StencilOpType {\n const gl = this.gl;\n return [gl.KEEP, gl.KEEP, gl.KEEP];\n }\n set(v: StencilOpType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty) return;\n this.gl.stencilOp(v[0], v[1], v[2]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class StencilTest extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n if (v) {\n gl.enable(gl.STENCIL_TEST);\n } else {\n gl.disable(gl.STENCIL_TEST);\n }\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthRange extends BaseValue {\n getDefault(): DepthRangeType {\n return [0, 1];\n }\n set(v: DepthRangeType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;\n this.gl.depthRange(v[0], v[1]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthTest extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n if (v) {\n gl.enable(gl.DEPTH_TEST);\n } else {\n gl.disable(gl.DEPTH_TEST);\n }\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthFunc extends BaseValue {\n getDefault(): DepthFuncType {\n return this.gl.LESS;\n }\n set(v: DepthFuncType) {\n if (v === this.current && !this.dirty) return;\n this.gl.depthFunc(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class Blend extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n if (v) {\n gl.enable(gl.BLEND);\n } else {\n gl.disable(gl.BLEND);\n }\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BlendFunc extends BaseValue {\n getDefault(): BlendFuncType {\n const gl = this.gl;\n return [gl.ONE, gl.ZERO];\n }\n set(v: BlendFuncType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;\n this.gl.blendFunc(v[0], v[1]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BlendColor extends BaseValue {\n getDefault(): Color {\n return Color.transparent;\n }\n set(v: Color) {\n const c = this.current;\n if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;\n this.gl.blendColor(v.r, v.g, v.b, v.a);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BlendEquation extends BaseValue {\n getDefault(): BlendEquationType {\n return this.gl.FUNC_ADD;\n }\n set(v: BlendEquationType) {\n if (v === this.current && !this.dirty) return;\n this.gl.blendEquation(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class CullFace extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n if (v) {\n gl.enable(gl.CULL_FACE);\n } else {\n gl.disable(gl.CULL_FACE);\n }\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class CullFaceSide extends BaseValue {\n getDefault(): CullFaceModeType {\n return this.gl.BACK;\n }\n set(v: CullFaceModeType) {\n if (v === this.current && !this.dirty) return;\n this.gl.cullFace(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class FrontFace extends BaseValue {\n getDefault(): FrontFaceType {\n return this.gl.CCW;\n }\n set(v: FrontFaceType) {\n if (v === this.current && !this.dirty) return;\n this.gl.frontFace(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class ProgramValue extends BaseValue {\n getDefault(): WebGLProgram {\n return null;\n }\n set(v?: WebGLProgram | null) {\n if (v === this.current && !this.dirty) return;\n this.gl.useProgram(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class ActiveTextureUnit extends BaseValue {\n getDefault(): TextureUnitType {\n return this.gl.TEXTURE0;\n }\n set(v: TextureUnitType) {\n if (v === this.current && !this.dirty) return;\n this.gl.activeTexture(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class Viewport extends BaseValue {\n getDefault(): ViewportType {\n const gl = this.gl;\n return [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight];\n }\n set(v: ViewportType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;\n this.gl.viewport(v[0], v[1], v[2], v[3]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindFramebuffer extends BaseValue {\n getDefault(): WebGLFramebuffer {\n return null;\n }\n set(v?: WebGLFramebuffer | null) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.bindFramebuffer(gl.FRAMEBUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindRenderbuffer extends BaseValue {\n getDefault(): WebGLRenderbuffer {\n return null;\n }\n set(v?: WebGLRenderbuffer | null) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.bindRenderbuffer(gl.RENDERBUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindTexture extends BaseValue {\n getDefault(): WebGLTexture {\n return null;\n }\n set(v?: WebGLTexture | null) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.bindTexture(gl.TEXTURE_2D, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindVertexBuffer extends BaseValue {\n getDefault(): WebGLBuffer {\n return null;\n }\n set(v?: WebGLBuffer | null) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.bindBuffer(gl.ARRAY_BUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindElementBuffer extends BaseValue {\n getDefault(): WebGLBuffer {\n return null;\n }\n set(v?: WebGLBuffer | null) {\n // Always rebind\n const gl = this.gl;\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindVertexArray extends BaseValue {\n getDefault(): WebGLVertexArrayObject | null {\n return null;\n }\n set(v: WebGLVertexArrayObject | null) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n\n if (isWebGL2(gl)) {\n gl.bindVertexArray(v);\n } else {\n gl.getExtension('OES_vertex_array_object')?.bindVertexArrayOES(v);\n }\n\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class PixelStoreUnpack extends BaseValue {\n getDefault(): number {\n return 4;\n }\n set(v: number) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class PixelStoreUnpackPremultiplyAlpha extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean): void {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, ((v as any)));\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class PixelStoreUnpackFlipY extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean): void {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, ((v as any)));\n this.current = v;\n this.dirty = false;\n }\n}\n\nclass FramebufferAttachment extends BaseValue {\n parent: WebGLFramebuffer;\n context: Context;\n\n constructor(context: Context, parent: WebGLFramebuffer) {\n super(context);\n this.context = context;\n this.parent = parent;\n }\n getDefault() {\n return null;\n }\n}\n\nexport class ColorAttachment extends FramebufferAttachment {\n setDirty() {\n this.dirty = true;\n }\n set(v?: WebGLTexture | null): void {\n if (v === this.current && !this.dirty) return;\n this.context.bindFramebuffer.set(this.parent);\n // note: it's possible to attach a renderbuffer to the color\n // attachment point, but thus far MBGL only uses textures for color\n const gl = this.gl;\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, v, 0);\n\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthAttachment extends FramebufferAttachment {\n set(v?: WebGLRenderbuffer | null): void {\n if (v === this.current && !this.dirty) return;\n this.context.bindFramebuffer.set(this.parent);\n // note: it's possible to attach a texture to the depth attachment\n // point, but thus far MBGL only uses renderbuffers for depth\n const gl = this.gl;\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthStencilAttachment extends FramebufferAttachment {\n set(v?: WebGLRenderbuffer | null): void {\n if (v === this.current && !this.dirty) return;\n this.context.bindFramebuffer.set(this.parent);\n // note: it's possible to attach a texture to the depth attachment\n // point, but thus far MBGL only uses renderbuffers for depth\n const gl = this.gl;\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n","import {ColorAttachment, DepthAttachment, DepthStencilAttachment} from './value';\n\nimport type {Context} from './context';\n\n/**\n * @internal\n * A framebuffer holder object\n */\nexport class Framebuffer {\n context: Context;\n width: number;\n height: number;\n framebuffer: WebGLFramebuffer;\n colorAttachment: ColorAttachment;\n depthAttachment: DepthAttachment;\n\n constructor(context: Context, width: number, height: number, hasDepth: boolean, hasStencil: boolean) {\n this.context = context;\n this.width = width;\n this.height = height;\n const gl = context.gl;\n const fbo = this.framebuffer = gl.createFramebuffer();\n\n this.colorAttachment = new ColorAttachment(context, fbo);\n if (hasDepth) {\n this.depthAttachment = hasStencil ? new DepthStencilAttachment(context, fbo) : new DepthAttachment(context, fbo);\n } else if (hasStencil) {\n throw new Error('Stencil cannot be set without depth');\n }\n if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {\n throw new Error('Framebuffer is not complete');\n }\n }\n\n destroy() {\n const gl = this.context.gl;\n\n const texture = this.colorAttachment.get();\n if (texture) gl.deleteTexture(texture);\n\n if (this.depthAttachment) {\n const renderbuffer = this.depthAttachment.get();\n if (renderbuffer) gl.deleteRenderbuffer(renderbuffer);\n }\n\n gl.deleteFramebuffer(this.framebuffer);\n }\n}\n","import {Color} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {BlendFuncType, ColorMaskType} from './types';\n\nconst ZERO = 0x0000;\nconst ONE = 0x0001;\nconst ONE_MINUS_SRC_ALPHA = 0x0303;\n\nexport class ColorMode {\n blendFunction: BlendFuncType;\n blendColor: Color;\n mask: ColorMaskType;\n\n constructor(blendFunction: BlendFuncType, blendColor: Color, mask: ColorMaskType) {\n this.blendFunction = blendFunction;\n this.blendColor = blendColor;\n this.mask = mask;\n }\n\n static Replace: BlendFuncType;\n\n static disabled: Readonly;\n static unblended: Readonly;\n static alphaBlended: Readonly;\n}\n\nColorMode.Replace = [ONE, ZERO];\n\nColorMode.disabled = new ColorMode(ColorMode.Replace, Color.transparent, [false, false, false, false]);\nColorMode.unblended = new ColorMode(ColorMode.Replace, Color.transparent, [true, true, true, true]);\nColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], Color.transparent, [true, true, true, true]);\n","import {IndexBuffer} from './index_buffer';\n\nimport {VertexBuffer} from './vertex_buffer';\nimport {Framebuffer} from './framebuffer';\nimport {DepthMode} from './depth_mode';\nimport {StencilMode} from './stencil_mode';\nimport {ColorMode} from './color_mode';\nimport {CullFaceMode} from './cull_face_mode';\nimport {deepEqual} from '../util/util';\nimport {ClearColor, ClearDepth, ClearStencil, ColorMask, DepthMask, StencilMask, StencilFunc, StencilOp, StencilTest, DepthRange, DepthTest, DepthFunc, Blend, BlendFunc, BlendColor, BlendEquation, CullFace, CullFaceSide, FrontFace, ProgramValue, ActiveTextureUnit, Viewport, BindFramebuffer, BindRenderbuffer, BindTexture, BindVertexBuffer, BindElementBuffer, BindVertexArray, PixelStoreUnpack, PixelStoreUnpackPremultiplyAlpha, PixelStoreUnpackFlipY} from './value';\n\nimport type {TriangleIndexArray, LineIndexArray, LineStripIndexArray} from '../data/index_array_type';\nimport type {\n StructArray,\n StructArrayMember\n} from '../util/struct_array';\nimport type {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {isWebGL2} from './webgl2';\n\ntype ClearArgs = {\n color?: Color;\n depth?: number;\n stencil?: number;\n};\n\n/**\n * @internal\n * A webgl wrapper class to allow injection, mocking and abstaction\n */\nexport class Context {\n gl: WebGLRenderingContext | WebGL2RenderingContext;\n\n currentNumAttributes: number;\n maxTextureSize: number;\n\n clearColor: ClearColor;\n clearDepth: ClearDepth;\n clearStencil: ClearStencil;\n colorMask: ColorMask;\n depthMask: DepthMask;\n stencilMask: StencilMask;\n stencilFunc: StencilFunc;\n stencilOp: StencilOp;\n stencilTest: StencilTest;\n depthRange: DepthRange;\n depthTest: DepthTest;\n depthFunc: DepthFunc;\n blend: Blend;\n blendFunc: BlendFunc;\n blendColor: BlendColor;\n blendEquation: BlendEquation;\n cullFace: CullFace;\n cullFaceSide: CullFaceSide;\n frontFace: FrontFace;\n program: ProgramValue;\n activeTexture: ActiveTextureUnit;\n viewport: Viewport;\n bindFramebuffer: BindFramebuffer;\n bindRenderbuffer: BindRenderbuffer;\n bindTexture: BindTexture;\n bindVertexBuffer: BindVertexBuffer;\n bindElementBuffer: BindElementBuffer;\n bindVertexArray: BindVertexArray;\n pixelStoreUnpack: PixelStoreUnpack;\n pixelStoreUnpackPremultiplyAlpha: PixelStoreUnpackPremultiplyAlpha;\n pixelStoreUnpackFlipY: PixelStoreUnpackFlipY;\n\n // eslint-disable-next-line camelcase\n extTextureFilterAnisotropic: EXT_texture_filter_anisotropic | null;\n extTextureFilterAnisotropicMax?: GLfloat;\n HALF_FLOAT?: GLenum;\n RGBA16F?: GLenum;\n RGB16F?: GLenum;\n\n constructor(gl: WebGLRenderingContext | WebGL2RenderingContext) {\n this.gl = gl;\n this.clearColor = new ClearColor(this);\n this.clearDepth = new ClearDepth(this);\n this.clearStencil = new ClearStencil(this);\n this.colorMask = new ColorMask(this);\n this.depthMask = new DepthMask(this);\n this.stencilMask = new StencilMask(this);\n this.stencilFunc = new StencilFunc(this);\n this.stencilOp = new StencilOp(this);\n this.stencilTest = new StencilTest(this);\n this.depthRange = new DepthRange(this);\n this.depthTest = new DepthTest(this);\n this.depthFunc = new DepthFunc(this);\n this.blend = new Blend(this);\n this.blendFunc = new BlendFunc(this);\n this.blendColor = new BlendColor(this);\n this.blendEquation = new BlendEquation(this);\n this.cullFace = new CullFace(this);\n this.cullFaceSide = new CullFaceSide(this);\n this.frontFace = new FrontFace(this);\n this.program = new ProgramValue(this);\n this.activeTexture = new ActiveTextureUnit(this);\n this.viewport = new Viewport(this);\n this.bindFramebuffer = new BindFramebuffer(this);\n this.bindRenderbuffer = new BindRenderbuffer(this);\n this.bindTexture = new BindTexture(this);\n this.bindVertexBuffer = new BindVertexBuffer(this);\n this.bindElementBuffer = new BindElementBuffer(this);\n this.bindVertexArray = new BindVertexArray(this);\n this.pixelStoreUnpack = new PixelStoreUnpack(this);\n this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this);\n this.pixelStoreUnpackFlipY = new PixelStoreUnpackFlipY(this);\n\n this.extTextureFilterAnisotropic = (\n gl.getExtension('EXT_texture_filter_anisotropic') ||\n gl.getExtension('MOZ_EXT_texture_filter_anisotropic') ||\n gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic')\n );\n\n if (this.extTextureFilterAnisotropic) {\n this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);\n }\n\n this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);\n\n if (isWebGL2(gl)) {\n this.HALF_FLOAT = gl.HALF_FLOAT;\n const extColorBufferHalfFloat = gl.getExtension('EXT_color_buffer_half_float');\n this.RGBA16F = gl.RGBA16F ?? extColorBufferHalfFloat?.RGBA16F_EXT;\n this.RGB16F = gl.RGB16F ?? extColorBufferHalfFloat?.RGB16F_EXT;\n gl.getExtension('EXT_color_buffer_float');\n } else {\n gl.getExtension('EXT_color_buffer_half_float');\n gl.getExtension('OES_texture_half_float_linear');\n const extTextureHalfFloat = gl.getExtension('OES_texture_half_float');\n this.HALF_FLOAT = extTextureHalfFloat?.HALF_FLOAT_OES;\n }\n }\n\n setDefault() {\n this.unbindVAO();\n\n this.clearColor.setDefault();\n this.clearDepth.setDefault();\n this.clearStencil.setDefault();\n this.colorMask.setDefault();\n this.depthMask.setDefault();\n this.stencilMask.setDefault();\n this.stencilFunc.setDefault();\n this.stencilOp.setDefault();\n this.stencilTest.setDefault();\n this.depthRange.setDefault();\n this.depthTest.setDefault();\n this.depthFunc.setDefault();\n this.blend.setDefault();\n this.blendFunc.setDefault();\n this.blendColor.setDefault();\n this.blendEquation.setDefault();\n this.cullFace.setDefault();\n this.cullFaceSide.setDefault();\n this.frontFace.setDefault();\n this.program.setDefault();\n this.activeTexture.setDefault();\n this.bindFramebuffer.setDefault();\n this.pixelStoreUnpack.setDefault();\n this.pixelStoreUnpackPremultiplyAlpha.setDefault();\n this.pixelStoreUnpackFlipY.setDefault();\n }\n\n setDirty() {\n this.clearColor.dirty = true;\n this.clearDepth.dirty = true;\n this.clearStencil.dirty = true;\n this.colorMask.dirty = true;\n this.depthMask.dirty = true;\n this.stencilMask.dirty = true;\n this.stencilFunc.dirty = true;\n this.stencilOp.dirty = true;\n this.stencilTest.dirty = true;\n this.depthRange.dirty = true;\n this.depthTest.dirty = true;\n this.depthFunc.dirty = true;\n this.blend.dirty = true;\n this.blendFunc.dirty = true;\n this.blendColor.dirty = true;\n this.blendEquation.dirty = true;\n this.cullFace.dirty = true;\n this.cullFaceSide.dirty = true;\n this.frontFace.dirty = true;\n this.program.dirty = true;\n this.activeTexture.dirty = true;\n this.viewport.dirty = true;\n this.bindFramebuffer.dirty = true;\n this.bindRenderbuffer.dirty = true;\n this.bindTexture.dirty = true;\n this.bindVertexBuffer.dirty = true;\n this.bindElementBuffer.dirty = true;\n this.bindVertexArray.dirty = true;\n this.pixelStoreUnpack.dirty = true;\n this.pixelStoreUnpackPremultiplyAlpha.dirty = true;\n this.pixelStoreUnpackFlipY.dirty = true;\n }\n\n createIndexBuffer(array: TriangleIndexArray | LineIndexArray | LineStripIndexArray, dynamicDraw?: boolean) {\n return new IndexBuffer(this, array, dynamicDraw);\n }\n\n createVertexBuffer(array: StructArray, attributes: ReadonlyArray, dynamicDraw?: boolean) {\n return new VertexBuffer(this, array, attributes, dynamicDraw);\n }\n\n createRenderbuffer(storageFormat: number, width: number, height: number) {\n const gl = this.gl;\n\n const rbo = gl.createRenderbuffer();\n this.bindRenderbuffer.set(rbo);\n gl.renderbufferStorage(gl.RENDERBUFFER, storageFormat, width, height);\n this.bindRenderbuffer.set(null);\n\n return rbo;\n }\n\n createFramebuffer(width: number, height: number, hasDepth: boolean, hasStencil: boolean) {\n return new Framebuffer(this, width, height, hasDepth, hasStencil);\n }\n\n clear({\n color,\n depth,\n stencil\n }: ClearArgs) {\n const gl = this.gl;\n let mask = 0;\n\n if (color) {\n mask |= gl.COLOR_BUFFER_BIT;\n this.clearColor.set(color);\n this.colorMask.set([true, true, true, true]);\n }\n\n if (typeof depth !== 'undefined') {\n mask |= gl.DEPTH_BUFFER_BIT;\n\n // Workaround for platforms where clearDepth doesn't seem to work\n // without resetting the depthRange. See https://github.com/mapbox/mapbox-gl-js/issues/3437\n this.depthRange.set([0, 1]);\n\n this.clearDepth.set(depth);\n this.depthMask.set(true);\n }\n\n if (typeof stencil !== 'undefined') {\n mask |= gl.STENCIL_BUFFER_BIT;\n this.clearStencil.set(stencil);\n this.stencilMask.set(0xFF);\n }\n\n gl.clear(mask);\n }\n\n setCullFace(cullFaceMode: Readonly) {\n if (cullFaceMode.enable === false) {\n this.cullFace.set(false);\n } else {\n this.cullFace.set(true);\n this.cullFaceSide.set(cullFaceMode.mode);\n this.frontFace.set(cullFaceMode.frontFace);\n }\n }\n\n setDepthMode(depthMode: Readonly) {\n if (depthMode.func === this.gl.ALWAYS && !depthMode.mask) {\n this.depthTest.set(false);\n } else {\n this.depthTest.set(true);\n this.depthFunc.set(depthMode.func);\n this.depthMask.set(depthMode.mask);\n this.depthRange.set(depthMode.range);\n }\n }\n\n setStencilMode(stencilMode: Readonly) {\n if (stencilMode.test.func === this.gl.ALWAYS && !stencilMode.mask) {\n this.stencilTest.set(false);\n } else {\n this.stencilTest.set(true);\n this.stencilMask.set(stencilMode.mask);\n this.stencilOp.set([stencilMode.fail, stencilMode.depthFail, stencilMode.pass]);\n this.stencilFunc.set({\n func: stencilMode.test.func,\n ref: stencilMode.ref,\n mask: stencilMode.test.mask\n });\n }\n }\n\n setColorMode(colorMode: Readonly) {\n if (deepEqual(colorMode.blendFunction, ColorMode.Replace)) {\n this.blend.set(false);\n } else {\n this.blend.set(true);\n this.blendFunc.set(colorMode.blendFunction);\n this.blendColor.set(colorMode.blendColor);\n }\n\n this.colorMask.set(colorMode.mask);\n }\n\n createVertexArray(): WebGLVertexArrayObject | undefined {\n if (isWebGL2(this.gl))\n return this.gl.createVertexArray();\n return this.gl.getExtension('OES_vertex_array_object')?.createVertexArrayOES();\n }\n\n deleteVertexArray(x: WebGLVertexArrayObject | undefined) {\n if (isWebGL2(this.gl))\n return this.gl.deleteVertexArray(x);\n return this.gl.getExtension('OES_vertex_array_object')?.deleteVertexArrayOES(x);\n }\n\n unbindVAO() {\n // Unbinding the VAO prevents other things (custom layers, new buffer creation) from\n // unintentionally changing the state of the last VAO used.\n this.bindVertexArray.set(null);\n }\n}\n","import type {DepthFuncType, DepthMaskType, DepthRangeType} from './types';\n\nconst ALWAYS = 0x0207;\n\nexport class DepthMode {\n func: DepthFuncType;\n mask: DepthMaskType;\n range: DepthRangeType;\n\n // DepthMask enums\n static ReadOnly: boolean;\n static ReadWrite: boolean;\n\n constructor(depthFunc: DepthFuncType, depthMask: DepthMaskType, depthRange: DepthRangeType) {\n this.func = depthFunc;\n this.mask = depthMask;\n this.range = depthRange;\n }\n\n static disabled: Readonly;\n}\n\nDepthMode.ReadOnly = false;\nDepthMode.ReadWrite = true;\n\nDepthMode.disabled = new DepthMode(ALWAYS, DepthMode.ReadOnly, [0, 1]);\n","import type {StencilOpConstant, StencilTestGL} from './types';\n\nconst ALWAYS = 0x0207;\nconst KEEP = 0x1E00;\n\nexport class StencilMode {\n test: StencilTestGL;\n ref: number;\n mask: number;\n fail: StencilOpConstant;\n depthFail: StencilOpConstant;\n pass: StencilOpConstant;\n\n constructor(test: StencilTestGL, ref: number, mask: number, fail: StencilOpConstant,\n depthFail: StencilOpConstant, pass: StencilOpConstant) {\n this.test = test;\n this.ref = ref;\n this.mask = mask;\n this.fail = fail;\n this.depthFail = depthFail;\n this.pass = pass;\n }\n\n static disabled: Readonly;\n}\n\nStencilMode.disabled = new StencilMode({func: ALWAYS, mask: 0}, 0, 0, KEEP, KEEP, KEEP);\n","import type {CullFaceModeType, FrontFaceType} from './types';\n\nconst BACK = 0x0405;\nconst CCW = 0x0901;\n\nexport class CullFaceMode {\n enable: boolean;\n mode: CullFaceModeType;\n frontFace: FrontFaceType;\n\n constructor(enable: boolean, mode: CullFaceModeType, frontFace: FrontFaceType) {\n this.enable = enable;\n this.mode = mode;\n this.frontFace = frontFace;\n }\n\n static disabled: Readonly;\n static backCCW: Readonly;\n}\n\nCullFaceMode.disabled = new CullFaceMode(false, BACK, CCW);\nCullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW);\n","import type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {StyleLayer} from '../style/style_layer';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport type {SymbolBucket} from '../data/bucket/symbol_bucket';\nimport {DepthMode} from '../gl/depth_mode';\nimport {StencilMode} from '../gl/stencil_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {collisionUniformValues, collisionCircleUniformValues} from './program/collision_program';\nimport {QuadTriangleArray, CollisionCircleLayoutArray} from '../data/array_types.g';\nimport {collisionCircleLayout} from '../data/bucket/symbol_attributes';\nimport {SegmentVector} from '../data/segment';\nimport {mat4} from 'gl-matrix';\nimport {VertexBuffer} from '../gl/vertex_buffer';\nimport {IndexBuffer} from '../gl/index_buffer';\n\ntype TileBatch = {\n circleArray: Array;\n circleOffset: number;\n transform: mat4;\n invTransform: mat4;\n coord: OverscaledTileID;\n};\n\nlet quadTriangles: QuadTriangleArray;\n\nexport function drawCollisionDebug(painter: Painter, sourceCache: SourceCache, layer: StyleLayer, coords: Array, isText: boolean) {\n const context = painter.context;\n const gl = context.gl;\n const program = painter.useProgram('collisionBox');\n const tileBatches: Array = [];\n let circleCount = 0;\n let circleOffset = 0;\n\n for (let i = 0; i < coords.length; i++) {\n const coord = coords[i];\n const tile = sourceCache.getTile(coord);\n const bucket: SymbolBucket = (tile.getBucket(layer) as any);\n if (!bucket) continue;\n const buffers = isText ? bucket.textCollisionBox : bucket.iconCollisionBox;\n // Get collision circle data of this bucket\n const circleArray: Array = bucket.collisionCircleArray;\n if (circleArray.length > 0) {\n // We need to know the projection matrix that was used for projecting collision circles to the screen.\n // This might vary between buckets as the symbol placement is a continuous process. This matrix is\n // required for transforming points from previous screen space to the current one\n const invTransform = mat4.create();\n\n mat4.mul(invTransform, bucket.placementInvProjMatrix, painter.transform.glCoordMatrix);\n mat4.mul(invTransform, invTransform, bucket.placementViewportMatrix);\n\n tileBatches.push({\n circleArray,\n circleOffset,\n transform: coord.posMatrix, // Ignore translation\n invTransform,\n coord\n });\n\n circleCount += circleArray.length / 4; // 4 values per circle\n circleOffset = circleCount;\n }\n\n // Draw collision boxes\n if (!buffers) {\n continue;\n }\n\n program.draw(context, gl.LINES,\n DepthMode.disabled, StencilMode.disabled,\n painter.colorModeForRenderPass(),\n CullFaceMode.disabled,\n collisionUniformValues(painter.transform, coord.posMatrix),\n painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord),\n layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer,\n buffers.segments, null, painter.transform.zoom, null, null,\n buffers.collisionVertexBuffer);\n }\n\n if (!isText || !tileBatches.length) {\n return;\n }\n\n // Render collision circles\n const circleProgram = painter.useProgram('collisionCircle');\n\n // Construct vertex data\n const vertexData = new CollisionCircleLayoutArray();\n vertexData.resize(circleCount * 4);\n vertexData._trim();\n\n let vertexOffset = 0;\n\n for (const batch of tileBatches) {\n for (let i = 0; i < batch.circleArray.length / 4; i++) {\n const circleIdx = i * 4;\n const x = batch.circleArray[circleIdx + 0];\n const y = batch.circleArray[circleIdx + 1];\n const radius = batch.circleArray[circleIdx + 2];\n const collision = batch.circleArray[circleIdx + 3];\n\n // 4 floats per vertex, 4 vertices per quad\n vertexData.emplace(vertexOffset++, x, y, radius, collision, 0);\n vertexData.emplace(vertexOffset++, x, y, radius, collision, 1);\n vertexData.emplace(vertexOffset++, x, y, radius, collision, 2);\n vertexData.emplace(vertexOffset++, x, y, radius, collision, 3);\n }\n }\n if (!quadTriangles || quadTriangles.length < circleCount * 2) {\n quadTriangles = createQuadTriangles(circleCount);\n }\n\n const indexBuffer: IndexBuffer = context.createIndexBuffer(quadTriangles, true);\n const vertexBuffer: VertexBuffer = context.createVertexBuffer(vertexData, collisionCircleLayout.members, true);\n\n // Render batches\n for (const batch of tileBatches) {\n const uniforms = collisionCircleUniformValues(\n batch.transform,\n batch.invTransform,\n painter.transform\n );\n\n circleProgram.draw(\n context,\n gl.TRIANGLES,\n DepthMode.disabled,\n StencilMode.disabled,\n painter.colorModeForRenderPass(),\n CullFaceMode.disabled,\n uniforms,\n painter.style.map.terrain && painter.style.map.terrain.getTerrainData(batch.coord),\n layer.id,\n vertexBuffer,\n indexBuffer,\n SegmentVector.simpleSegment(0, batch.circleOffset * 2, batch.circleArray.length, batch.circleArray.length / 2),\n null,\n painter.transform.zoom,\n null,\n null,\n null);\n }\n\n vertexBuffer.destroy();\n indexBuffer.destroy();\n}\n\nfunction createQuadTriangles(quadCount: number): QuadTriangleArray {\n const triCount = quadCount * 2;\n const array = new QuadTriangleArray();\n\n array.resize(triCount);\n array._trim();\n\n // Two triangles and 4 vertices per quad.\n for (let i = 0; i < triCount; i++) {\n const idx = i * 6;\n\n array.uint16[idx + 0] = i * 4 + 0;\n array.uint16[idx + 1] = i * 4 + 1;\n array.uint16[idx + 2] = i * 4 + 2;\n array.uint16[idx + 3] = i * 4 + 2;\n array.uint16[idx + 4] = i * 4 + 3;\n array.uint16[idx + 5] = i * 4 + 0;\n }\n\n return array;\n}\n","import Point from '@mapbox/point-geometry';\nimport {drawCollisionDebug} from './draw_collision_debug';\n\nimport {SegmentVector} from '../data/segment';\nimport {pixelsToTileUnits} from '../source/pixels_to_tile_units';\nimport * as symbolProjection from '../symbol/projection';\nimport {EvaluatedZoomSize, evaluateSizeForFeature, evaluateSizeForZoom} from '../symbol/symbol_size';\nimport {mat4} from 'gl-matrix';\nimport {StencilMode} from '../gl/stencil_mode';\nimport {DepthMode} from '../gl/depth_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {addDynamicAttributes} from '../data/bucket/symbol_bucket';\n\nimport {getAnchorAlignment, WritingMode} from '../symbol/shaping';\nimport ONE_EM from '../symbol/one_em';\n\nimport {\n SymbolIconUniformsType,\n symbolIconUniformValues,\n symbolSDFUniformValues,\n symbolTextAndIconUniformValues\n} from './program/symbol_program';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {SymbolStyleLayer} from '../style/style_layer/symbol_style_layer';\n\nimport type {Texture, TextureFilter} from '../render/texture';\nimport type {OverscaledTileID, UnwrappedTileID} from '../source/tile_id';\nimport type {UniformValues} from './uniform_binding';\nimport type {SymbolSDFUniformsType} from '../render/program/symbol_program';\nimport type {CrossTileID, VariableOffset} from '../symbol/placement';\nimport type {SymbolBucket, SymbolBuffers} from '../data/bucket/symbol_bucket';\nimport type {TerrainData} from '../render/terrain';\nimport type {SymbolLayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Transform} from '../geo/transform';\nimport type {ColorMode} from '../gl/color_mode';\nimport type {Program} from './program';\nimport type {TextAnchor} from '../style/style_layer/variable_text_anchor';\nimport {createProjection, Projection} from '../geo/projection/projection';\n\ntype SymbolTileRenderState = {\n segments: SegmentVector;\n sortKey: number;\n terrainData: TerrainData;\n state: {\n program: Program;\n buffers: SymbolBuffers;\n uniformValues: UniformValues;\n atlasTexture: Texture;\n atlasTextureIcon: Texture | null;\n atlasInterpolation: TextureFilter;\n atlasInterpolationIcon: TextureFilter;\n isSDF: boolean;\n hasHalo: boolean;\n };\n};\n\nconst identityMat4 = mat4.identity(new Float32Array(16));\n\nexport function drawSymbols(painter: Painter, sourceCache: SourceCache, layer: SymbolStyleLayer, coords: Array, variableOffsets: {\n [_ in CrossTileID]: VariableOffset;\n}) {\n if (painter.renderPass !== 'translucent') return;\n\n // Disable the stencil test so that labels aren't clipped to tile boundaries.\n const stencilMode = StencilMode.disabled;\n const colorMode = painter.colorModeForRenderPass();\n const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset');\n\n //Compute variable-offsets before painting since icons and text data positioning\n //depend on each other in this case.\n if (hasVariablePlacement) {\n updateVariableAnchors(coords, painter, layer, sourceCache,\n layer.layout.get('text-rotation-alignment'),\n layer.layout.get('text-pitch-alignment'),\n layer.paint.get('text-translate'),\n layer.paint.get('text-translate-anchor'),\n variableOffsets\n );\n }\n\n if (layer.paint.get('icon-opacity').constantOr(1) !== 0) {\n drawLayerSymbols(painter, sourceCache, layer, coords, false,\n layer.paint.get('icon-translate'),\n layer.paint.get('icon-translate-anchor'),\n layer.layout.get('icon-rotation-alignment'),\n layer.layout.get('icon-pitch-alignment'),\n layer.layout.get('icon-keep-upright'),\n stencilMode, colorMode\n );\n }\n\n if (layer.paint.get('text-opacity').constantOr(1) !== 0) {\n drawLayerSymbols(painter, sourceCache, layer, coords, true,\n layer.paint.get('text-translate'),\n layer.paint.get('text-translate-anchor'),\n layer.layout.get('text-rotation-alignment'),\n layer.layout.get('text-pitch-alignment'),\n layer.layout.get('text-keep-upright'),\n stencilMode, colorMode\n );\n }\n\n if (sourceCache.map.showCollisionBoxes) {\n drawCollisionDebug(painter, sourceCache, layer, coords, true);\n drawCollisionDebug(painter, sourceCache, layer, coords, false);\n }\n}\n\nfunction calculateVariableRenderShift(\n anchor: TextAnchor,\n width: number,\n height: number,\n textOffset: [number, number],\n textBoxScale: number,\n renderTextSize: number): Point {\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);\n const shiftX = -(horizontalAlign - 0.5) * width;\n const shiftY = -(verticalAlign - 0.5) * height;\n return new Point(\n (shiftX / textBoxScale + textOffset[0]) * renderTextSize,\n (shiftY / textBoxScale + textOffset[1]) * renderTextSize\n );\n}\n\nfunction updateVariableAnchors(coords: Array,\n painter: Painter,\n layer:SymbolStyleLayer, sourceCache: SourceCache,\n rotationAlignment: SymbolLayerSpecification['layout']['text-rotation-alignment'],\n pitchAlignment: SymbolLayerSpecification['layout']['text-pitch-alignment'],\n translate: [number, number],\n translateAnchor: 'map' | 'viewport',\n variableOffsets: {[_ in CrossTileID]: VariableOffset}) {\n const transform = painter.transform;\n const projection = createProjection();\n const rotateWithMap = rotationAlignment === 'map';\n const pitchWithMap = pitchAlignment === 'map';\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n const bucket = tile.getBucket(layer) as SymbolBucket;\n if (!bucket || !bucket.text || !bucket.text.segments.get().length) continue;\n\n const sizeData = bucket.textSizeData;\n const size = evaluateSizeForZoom(sizeData, transform.zoom);\n\n const pixelToTileScale = pixelsToTileUnits(tile, 1, painter.transform.zoom);\n const labelPlaneMatrix = symbolProjection.getLabelPlaneMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, pixelToTileScale);\n const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' && bucket.hasIconData();\n\n if (size) {\n const tileScale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);\n const getElevation = painter.style.map.terrain ? (x: number, y: number) => painter.style.map.terrain.getElevation(coord, x, y) : null;\n const translation = projection.translatePosition(transform, tile, translate, translateAnchor);\n updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets,\n transform, labelPlaneMatrix, coord.posMatrix, tileScale, size, updateTextFitIcon, projection, translation, coord.toUnwrapped(), getElevation);\n }\n }\n}\n\nfunction getShiftedAnchor(projectedAnchorPoint: Point, projectionContext: symbolProjection.SymbolProjectionContext, rotateWithMap, shift: Point, transformAngle: number, pitchedTextShiftCorrection: number) {\n // Usual case is that we take the projected anchor and add the pixel-based shift\n // calculated earlier. In the (somewhat weird) case of pitch-aligned text, we add an equivalent\n // tile-unit based shift to the anchor before projecting to the label plane.\n const translatedAnchor = projectionContext.tileAnchorPoint.add(new Point(projectionContext.translation[0], projectionContext.translation[1]));\n if (projectionContext.pitchWithMap) {\n let adjustedShift = shift.mult(pitchedTextShiftCorrection);\n if (!rotateWithMap) {\n adjustedShift = adjustedShift.rotate(-transformAngle);\n }\n const tileAnchorShifted = translatedAnchor.add(adjustedShift);\n return symbolProjection.project(tileAnchorShifted.x, tileAnchorShifted.y, projectionContext.labelPlaneMatrix, projectionContext.getElevation).point;\n } else {\n if (rotateWithMap) {\n // Compute the angle with which to rotate the anchor, so that it is aligned with\n // the map's actual east-west axis. Very similar to what is done in the shader.\n const projectedAnchorRight = symbolProjection.projectTileCoordinatesToViewport(projectionContext.tileAnchorPoint.x + 1, projectionContext.tileAnchorPoint.y, projectionContext);\n const east = projectedAnchorRight.point.sub(projectedAnchorPoint);\n const angle = Math.atan(east.y / east.x) + (east.x < 0 ? Math.PI : 0);\n return projectedAnchorPoint.add(shift.rotate(angle));\n } else {\n return projectedAnchorPoint.add(shift);\n }\n }\n}\n\nfunction updateVariableAnchorsForBucket(\n bucket: SymbolBucket,\n rotateWithMap: boolean,\n pitchWithMap: boolean,\n variableOffsets: {[_ in CrossTileID]: VariableOffset},\n transform: Transform,\n labelPlaneMatrix: mat4,\n posMatrix: mat4,\n tileScale: number,\n size: EvaluatedZoomSize,\n updateTextFitIcon: boolean,\n projection: Projection,\n translation: [number, number],\n unwrappedTileID: UnwrappedTileID,\n getElevation: (x: number, y: number) => number) {\n const placedSymbols = bucket.text.placedSymbolArray;\n const dynamicTextLayoutVertexArray = bucket.text.dynamicLayoutVertexArray;\n const dynamicIconLayoutVertexArray = bucket.icon.dynamicLayoutVertexArray;\n const placedTextShifts = {};\n\n dynamicTextLayoutVertexArray.clear();\n for (let s = 0; s < placedSymbols.length; s++) {\n const symbol = placedSymbols.get(s);\n const skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation;\n const variableOffset = (!symbol.hidden && symbol.crossTileID && !skipOrientation) ? variableOffsets[symbol.crossTileID] : null;\n\n if (!variableOffset) {\n // These symbols are from a justification that is not being used, or a label that wasn't placed\n // so we don't need to do the extra math to figure out what incremental shift to apply.\n symbolProjection.hideGlyphs(symbol.numGlyphs, dynamicTextLayoutVertexArray);\n } else {\n const tileAnchor = new Point(symbol.anchorX, symbol.anchorY);\n const projectionContext = {\n getElevation,\n width: transform.width,\n height: transform.height,\n labelPlaneMatrix,\n lineVertexArray: null,\n pitchWithMap,\n projection,\n projectionCache: null,\n tileAnchorPoint: tileAnchor,\n translation,\n unwrappedTileID\n };\n const projectedAnchor = pitchWithMap ?\n symbolProjection.project(tileAnchor.x, tileAnchor.y, posMatrix, getElevation) :\n symbolProjection.projectTileCoordinatesToViewport(tileAnchor.x, tileAnchor.y, projectionContext);\n const perspectiveRatio = symbolProjection.getPerspectiveRatio(transform.cameraToCenterDistance, projectedAnchor.signedDistanceFromCamera);\n let renderTextSize = evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / ONE_EM;\n if (pitchWithMap) {\n // Go from size in pixels to equivalent size in tile units\n renderTextSize *= bucket.tilePixelRatio / tileScale;\n }\n\n const {width, height, anchor, textOffset, textBoxScale} = variableOffset;\n const shift = calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize);\n\n const pitchedTextCorrection = projection.getPitchedTextCorrection(transform, tileAnchor.add(new Point(translation[0], translation[1])), unwrappedTileID);\n const shiftedAnchor = getShiftedAnchor(projectedAnchor.point, projectionContext, rotateWithMap, shift, transform.angle, pitchedTextCorrection);\n\n const angle = (bucket.allowVerticalPlacement && symbol.placedOrientation === WritingMode.vertical) ? Math.PI / 2 : 0;\n for (let g = 0; g < symbol.numGlyphs; g++) {\n addDynamicAttributes(dynamicTextLayoutVertexArray, shiftedAnchor, angle);\n }\n //Only offset horizontal text icons\n if (updateTextFitIcon && symbol.associatedIconIndex >= 0) {\n placedTextShifts[symbol.associatedIconIndex] = {shiftedAnchor, angle};\n }\n }\n }\n\n if (updateTextFitIcon) {\n dynamicIconLayoutVertexArray.clear();\n const placedIcons = bucket.icon.placedSymbolArray;\n for (let i = 0; i < placedIcons.length; i++) {\n const placedIcon = placedIcons.get(i);\n if (placedIcon.hidden) {\n symbolProjection.hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);\n } else {\n const shift = placedTextShifts[i];\n if (!shift) {\n symbolProjection.hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);\n } else {\n for (let g = 0; g < placedIcon.numGlyphs; g++) {\n addDynamicAttributes(dynamicIconLayoutVertexArray, shift.shiftedAnchor, shift.angle);\n }\n }\n }\n }\n bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray);\n }\n bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray);\n}\n\nfunction getSymbolProgramName(isSDF: boolean, isText: boolean, bucket: SymbolBucket) {\n if (bucket.iconsInText && isText) {\n return 'symbolTextAndIcon';\n } else if (isSDF) {\n return 'symbolSDF';\n } else {\n return 'symbolIcon';\n }\n}\n\nfunction drawLayerSymbols(\n painter: Painter,\n sourceCache: SourceCache,\n layer: SymbolStyleLayer,\n coords: Array,\n isText: boolean,\n translate: [number, number],\n translateAnchor: 'map' | 'viewport',\n rotationAlignment: SymbolLayerSpecification['layout']['text-rotation-alignment'],\n pitchAlignment: SymbolLayerSpecification['layout']['text-pitch-alignment'],\n keepUpright: boolean,\n stencilMode: StencilMode,\n colorMode: Readonly) {\n\n const context = painter.context;\n const gl = context.gl;\n const tr = painter.transform;\n const projection = createProjection();\n\n const rotateWithMap = rotationAlignment === 'map';\n const pitchWithMap = pitchAlignment === 'map';\n const alongLine = rotationAlignment !== 'viewport' && layer.layout.get('symbol-placement') !== 'point';\n // Line label rotation happens in `updateLineLabels`\n // Pitched point labels are automatically rotated by the labelPlaneMatrix projection\n // Unpitched point labels need to have their rotation applied after projection\n const rotateInShader = rotateWithMap && !pitchWithMap && !alongLine;\n\n const isViewportLine = !pitchWithMap && alongLine;\n\n const hasSortKey = !layer.layout.get('symbol-sort-key').isConstant();\n let sortFeaturesByKey = false;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n\n const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset');\n\n const tileRenderState: Array = [];\n\n const pitchedTextRescaling = projection.getCircleRadiusCorrection(tr);\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n const bucket = tile.getBucket(layer) as SymbolBucket;\n if (!bucket) continue;\n const buffers = isText ? bucket.text : bucket.icon;\n\n if (!buffers || !buffers.segments.get().length || !buffers.hasVisibleVertices) continue;\n const programConfiguration = buffers.programConfigurations.get(layer.id);\n\n const isSDF = isText || bucket.sdfIcons;\n\n const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;\n const transformed = pitchWithMap || tr.pitch !== 0;\n\n const program = painter.useProgram(getSymbolProgramName(isSDF, isText, bucket), programConfiguration);\n const size = evaluateSizeForZoom(sizeData, tr.zoom);\n const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord);\n\n let texSize: [number, number];\n let texSizeIcon: [number, number] = [0, 0];\n let atlasTexture: Texture;\n let atlasInterpolation: TextureFilter;\n let atlasTextureIcon = null;\n let atlasInterpolationIcon: TextureFilter;\n if (isText) {\n atlasTexture = tile.glyphAtlasTexture;\n atlasInterpolation = gl.LINEAR;\n texSize = tile.glyphAtlasTexture.size;\n if (bucket.iconsInText) {\n texSizeIcon = tile.imageAtlasTexture.size;\n atlasTextureIcon = tile.imageAtlasTexture;\n const zoomDependentSize = sizeData.kind === 'composite' || sizeData.kind === 'camera';\n atlasInterpolationIcon = transformed || painter.options.rotating || painter.options.zooming || zoomDependentSize ? gl.LINEAR : gl.NEAREST;\n }\n } else {\n const iconScaled = layer.layout.get('icon-size').constantOr(0) !== 1 || bucket.iconsNeedLinear;\n atlasTexture = tile.imageAtlasTexture;\n atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || transformed ?\n gl.LINEAR :\n gl.NEAREST;\n texSize = tile.imageAtlasTexture.size;\n }\n\n const s = pixelsToTileUnits(tile, 1, painter.transform.zoom);\n const baseMatrix = isViewportLine ? coord.posMatrix : identityMat4;\n const labelPlaneMatrix = symbolProjection.getLabelPlaneMatrix(baseMatrix, pitchWithMap, rotateWithMap, painter.transform, s);\n const glCoordMatrixForShader = symbolProjection.getGlCoordMatrix(baseMatrix, pitchWithMap, rotateWithMap, painter.transform, s);\n const glCoordMatrixForSymbolPlacement = symbolProjection.getGlCoordMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s);\n\n const translation = projection.translatePosition(painter.transform, tile, translate, translateAnchor);\n\n const hasVariableAnchors = hasVariablePlacement && bucket.hasTextData();\n const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' &&\n hasVariableAnchors &&\n bucket.hasIconData();\n\n if (alongLine) {\n const getElevation = painter.style.map.terrain ? (x: number, y: number) => painter.style.map.terrain.getElevation(coord, x, y) : null;\n const rotateToLine = layer.layout.get('text-rotation-alignment') === 'map';\n symbolProjection.updateLineLabels(bucket, coord.posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrixForSymbolPlacement, pitchWithMap, keepUpright, rotateToLine, projection, coord.toUnwrapped(), tr.width, tr.height, translation, getElevation);\n }\n\n const matrix = coord.posMatrix; // formerly also incorporated translate and translate-anchor\n const shaderVariableAnchor = (isText && hasVariablePlacement) || updateTextFitIcon;\n const noLabelPlane = (alongLine || shaderVariableAnchor);\n const uLabelPlaneMatrix = noLabelPlane ? identityMat4 : labelPlaneMatrix;\n const uglCoordMatrix = glCoordMatrixForShader; // formerly also incorporated translate and translate-anchor\n\n const hasHalo = isSDF && layer.paint.get(isText ? 'text-halo-width' : 'icon-halo-width').constantOr(1) !== 0;\n\n let uniformValues: UniformValues;\n if (isSDF) {\n if (!bucket.iconsInText) {\n uniformValues = symbolSDFUniformValues(sizeData.kind,\n size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix,\n uLabelPlaneMatrix, uglCoordMatrix, translation, isText, texSize, true, pitchedTextRescaling);\n } else {\n uniformValues = symbolTextAndIconUniformValues(sizeData.kind,\n size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix,\n uLabelPlaneMatrix, uglCoordMatrix, translation, texSize, texSizeIcon, pitchedTextRescaling);\n }\n } else {\n uniformValues = symbolIconUniformValues(sizeData.kind,\n size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix,\n uLabelPlaneMatrix, uglCoordMatrix, translation, isText, texSize, pitchedTextRescaling);\n }\n\n const state = {\n program,\n buffers,\n uniformValues,\n atlasTexture,\n atlasTextureIcon,\n atlasInterpolation,\n atlasInterpolationIcon,\n isSDF,\n hasHalo\n };\n\n if (hasSortKey && bucket.canOverlap) {\n sortFeaturesByKey = true;\n const oldSegments = buffers.segments.get();\n for (const segment of oldSegments) {\n tileRenderState.push({\n segments: new SegmentVector([segment]),\n sortKey: segment.sortKey,\n state,\n terrainData\n });\n }\n } else {\n tileRenderState.push({\n segments: buffers.segments,\n sortKey: 0,\n state,\n terrainData\n });\n }\n }\n\n if (sortFeaturesByKey) {\n tileRenderState.sort((a, b) => a.sortKey - b.sortKey);\n }\n\n for (const segmentState of tileRenderState) {\n const state = segmentState.state;\n\n context.activeTexture.set(gl.TEXTURE0);\n state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE);\n if (state.atlasTextureIcon) {\n context.activeTexture.set(gl.TEXTURE1);\n if (state.atlasTextureIcon) {\n state.atlasTextureIcon.bind(state.atlasInterpolationIcon, gl.CLAMP_TO_EDGE);\n }\n }\n\n if (state.isSDF) {\n const uniformValues = state.uniformValues;\n if (state.hasHalo) {\n uniformValues['u_is_halo'] = 1;\n drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, uniformValues, segmentState.terrainData);\n }\n uniformValues['u_is_halo'] = 0;\n }\n drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, state.uniformValues, segmentState.terrainData);\n }\n}\n\nfunction drawSymbolElements(\n buffers: SymbolBuffers,\n segments: SegmentVector,\n layer: SymbolStyleLayer,\n painter: Painter,\n program: Program,\n depthMode: Readonly,\n stencilMode: StencilMode,\n colorMode: Readonly,\n uniformValues: UniformValues,\n terrainData: TerrainData) {\n const context = painter.context;\n const gl = context.gl;\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, terrainData, layer.id, buffers.layoutVertexBuffer,\n buffers.indexBuffer, segments, layer.paint,\n painter.transform.zoom, buffers.programConfigurations.get(layer.id),\n buffers.dynamicLayoutVertexBuffer, buffers.opacityVertexBuffer);\n}\n","import {Texture} from './texture';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {DepthMode} from '../gl/depth_mode';\nimport {StencilMode} from '../gl/stencil_mode';\nimport {ColorMode} from '../gl/color_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {Context} from '../gl/context';\nimport {Framebuffer} from '../gl/framebuffer';\nimport {Tile} from '../source/tile';\nimport {\n heatmapUniformValues,\n heatmapTextureUniformValues\n} from './program/heatmap_program';\nimport {HEATMAP_FULL_RENDER_FBO_KEY} from '../style/style_layer/heatmap_style_layer';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {HeatmapStyleLayer} from '../style/style_layer/heatmap_style_layer';\nimport type {HeatmapBucket} from '../data/bucket/heatmap_bucket';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport function drawHeatmap(painter: Painter, sourceCache: SourceCache, layer: HeatmapStyleLayer, tileIDs: Array) {\n if (layer.paint.get('heatmap-opacity') === 0) {\n return;\n }\n const context = painter.context;\n\n if (painter.style.map.terrain) {\n for (const coord of tileIDs) {\n const tile = sourceCache.getTile(coord);\n // Skip tiles that have uncovered parents to avoid flickering; we don't need\n // to use complex tile masking here because the change between zoom levels is subtle,\n // so it's fine to simply render the parent until all its 4 children are loaded\n if (sourceCache.hasRenderableParent(coord)) continue;\n if (painter.renderPass === 'offscreen') {\n prepareHeatmapTerrain(painter, tile, layer, coord);\n } else if (painter.renderPass === 'translucent') {\n renderHeatmapTerrain(painter, layer, coord);\n }\n }\n context.viewport.set([0, 0, painter.width, painter.height]);\n } else {\n if (painter.renderPass === 'offscreen') {\n prepareHeatmapFlat(painter, sourceCache, layer, tileIDs);\n } else if (painter.renderPass === 'translucent') {\n renderHeatmapFlat(painter, layer);\n }\n\n }\n}\n\nfunction prepareHeatmapFlat(painter: Painter, sourceCache: SourceCache, layer: HeatmapStyleLayer, coords: Array) {\n const context = painter.context;\n const gl = context.gl;\n\n // Allow kernels to be drawn across boundaries, so that\n // large kernels are not clipped to tiles\n const stencilMode = StencilMode.disabled;\n // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula\n const colorMode = new ColorMode([gl.ONE, gl.ONE], Color.transparent, [true, true, true, true]);\n\n bindFramebuffer(context, painter, layer);\n\n context.clear({color: Color.transparent});\n\n for (let i = 0; i < coords.length; i++) {\n const coord = coords[i];\n\n // Skip tiles that have uncovered parents to avoid flickering; we don't need\n // to use complex tile masking here because the change between zoom levels is subtle,\n // so it's fine to simply render the parent until all its 4 children are loaded\n if (sourceCache.hasRenderableParent(coord)) continue;\n\n const tile = sourceCache.getTile(coord);\n const bucket: HeatmapBucket = (tile.getBucket(layer) as any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram('heatmap', programConfiguration);\n const {zoom} = painter.transform;\n\n program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled,\n heatmapUniformValues(coord.posMatrix, tile, zoom, layer.paint.get('heatmap-intensity')), null,\n layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer,\n bucket.segments, layer.paint, painter.transform.zoom,\n programConfiguration);\n }\n\n context.viewport.set([0, 0, painter.width, painter.height]);\n}\n\nfunction renderHeatmapFlat(painter: Painter, layer: HeatmapStyleLayer) {\n const context = painter.context;\n const gl = context.gl;\n\n context.setColorMode(painter.colorModeForRenderPass());\n\n // Here we bind two different textures from which we'll sample in drawing\n // heatmaps: the kernel texture, prepared in the offscreen pass, and a\n // color ramp texture.\n const fbo = layer.heatmapFbos.get(HEATMAP_FULL_RENDER_FBO_KEY);\n if (!fbo) return;\n context.activeTexture.set(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n\n context.activeTexture.set(gl.TEXTURE1);\n const colorRampTexture = getColorRampTexture(context, layer);\n colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n\n painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES,\n DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled,\n heatmapTextureUniformValues(painter, layer, 0, 1), null,\n layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer,\n painter.viewportSegments, layer.paint, painter.transform.zoom);\n}\n\nfunction prepareHeatmapTerrain(painter: Painter, tile: Tile, layer: HeatmapStyleLayer, coord: OverscaledTileID) {\n const context = painter.context;\n const gl = context.gl;\n\n const stencilMode = StencilMode.disabled;\n // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula\n const colorMode = new ColorMode([gl.ONE, gl.ONE], Color.transparent, [true, true, true, true]);\n\n const bucket: HeatmapBucket = (tile.getBucket(layer) as any);\n if (!bucket) return;\n\n const tileKey = coord.key;\n let fbo = layer.heatmapFbos.get(tileKey);\n if (!fbo) {\n fbo = createHeatmapFbo(context, tile.tileSize, tile.tileSize);\n layer.heatmapFbos.set(tileKey, fbo);\n }\n\n context.bindFramebuffer.set(fbo.framebuffer);\n context.viewport.set([0, 0, tile.tileSize, tile.tileSize]);\n\n context.clear({color: Color.transparent});\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram('heatmap', programConfiguration);\n\n const terrainData = painter.style.map.terrain.getTerrainData(coord);\n program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled,\n heatmapUniformValues(coord.posMatrix, tile, painter.transform.zoom, layer.paint.get('heatmap-intensity')), terrainData,\n layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer,\n bucket.segments, layer.paint, painter.transform.zoom,\n programConfiguration);\n}\n\nfunction renderHeatmapTerrain(painter: Painter, layer: HeatmapStyleLayer, coord: OverscaledTileID) {\n const context = painter.context;\n const gl = context.gl;\n\n context.setColorMode(painter.colorModeForRenderPass());\n\n const colorRampTexture = getColorRampTexture(context, layer);\n\n // Here we bind two different textures from which we'll sample in drawing\n // heatmaps: the kernel texture, prepared in the offscreen pass, and a\n // color ramp texture.\n const tileKey = coord.key;\n const fbo = layer.heatmapFbos.get(tileKey);\n if (!fbo) return;\n\n context.activeTexture.set(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n\n context.activeTexture.set(gl.TEXTURE1);\n colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n\n painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES,\n DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled,\n heatmapTextureUniformValues(painter, layer, 0, 1), null,\n layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer,\n painter.rasterBoundsSegments, layer.paint, painter.transform.zoom);\n\n // destroy the FBO after rendering\n fbo.destroy();\n layer.heatmapFbos.delete(tileKey);\n}\n\nfunction bindFramebuffer(context: Context, painter: Painter, layer: HeatmapStyleLayer) {\n const gl = context.gl;\n context.activeTexture.set(gl.TEXTURE1);\n\n // Use a 4x downscaled screen texture for better performance\n context.viewport.set([0, 0, painter.width / 4, painter.height / 4]);\n\n let fbo = layer.heatmapFbos.get(HEATMAP_FULL_RENDER_FBO_KEY);\n\n if (!fbo) {\n fbo = createHeatmapFbo(context, painter.width / 4, painter.height / 4);\n layer.heatmapFbos.set(HEATMAP_FULL_RENDER_FBO_KEY, fbo);\n } else {\n gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n context.bindFramebuffer.set(fbo.framebuffer);\n }\n}\n\nfunction createHeatmapFbo(context: Context, width: number, height: number): Framebuffer {\n const gl = context.gl;\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, 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 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n\n // Use the higher precision half-float texture where available (producing much smoother looking heatmaps);\n // Otherwise, fall back to a low precision texture\n const numType = context.HALF_FLOAT ?? gl.UNSIGNED_BYTE;\n const internalFormat = context.RGBA16F ?? gl.RGBA;\n\n gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA, numType, null);\n\n const fbo = context.createFramebuffer(width, height, false, false);\n fbo.colorAttachment.set(texture);\n\n return fbo;\n}\n\nfunction getColorRampTexture(context: Context, layer: HeatmapStyleLayer): Texture {\n if (!layer.colorRampTexture) {\n layer.colorRampTexture = new Texture(context, layer.colorRamp, context.gl.RGBA);\n }\n return layer.colorRampTexture;\n}\n","import type {CrossFaded} from '../style/properties';\nimport type {ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\nimport type {Tile} from '../source/tile';\nimport type {ProgramConfiguration} from '../data/program_configuration';\nimport type {FillExtrusionStyleLayer} from '../style/style_layer/fill_extrusion_style_layer';\nimport type {FillStyleLayer} from '../style/style_layer/fill_style_layer';\n\n/**\n * A simple helper shared by draw_fill and draw_fill_extrusions to find the correct pattern positions AND update program.\n * For transitionable properties, especially 'fill-pattern' and 'fill-extrusion-pattern', while rendering certain frames\n * tile.imageAtlas has been updated by worker to hold the new pattern only, but rendering code is still looking for the previous image.\n * The mismatch was causing setConstantPatternPositions method not being called and pixelRatio was always the\n * default of 1, instead of actual values set by original map.addImage.\n *\n * @param programConfiguration - to be used to set pattern position and device pixel ratio.\n * @param propertyName - 'fill-pattern' or 'fill-extrusion-pattern' property key\n * @param constantPattern - either 'fill-pattern' or 'fill-extrusion-pattern' property value\n * @param tile - current tile being drawn\n * @param layer - current layer being rendered\n */\nexport function updatePatternPositionsInProgram(\n programConfiguration: ProgramConfiguration,\n propertyName: 'fill-pattern' | 'fill-extrusion-pattern',\n constantPattern: CrossFaded,\n tile: Tile,\n layer: FillStyleLayer | FillExtrusionStyleLayer): void {\n\n if (!constantPattern || !tile || !tile.imageAtlas) {\n return;\n }\n\n const patternPositions = tile.imageAtlas.patternPositions;\n let posTo = patternPositions[constantPattern.to.toString()];\n let posFrom = patternPositions[constantPattern.from.toString()];\n\n // https://github.com/maplibre/maplibre-gl-js/issues/3377\n if (!posTo && posFrom) posTo = posFrom;\n if (!posFrom && posTo) posFrom = posTo;\n\n // try again in case patternPositions has been updated by worker\n if (!posTo || !posFrom) {\n const transitioned = layer.getPaintProperty(propertyName) as string;\n posTo = patternPositions[transitioned];\n posFrom = patternPositions[transitioned];\n }\n\n if (posTo && posFrom) {\n programConfiguration.setConstantPatternPositions(posTo, posFrom);\n }\n}\n","import {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {DepthMode} from '../gl/depth_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {ColorMode} from '../gl/color_mode';\nimport {\n fillUniformValues,\n fillPatternUniformValues,\n fillOutlineUniformValues,\n fillOutlinePatternUniformValues\n} from './program/fill_program';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {FillStyleLayer} from '../style/style_layer/fill_style_layer';\nimport type {FillBucket} from '../data/bucket/fill_bucket';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport {updatePatternPositionsInProgram} from './update_pattern_positions_in_program';\n\nexport function drawFill(painter: Painter, sourceCache: SourceCache, layer: FillStyleLayer, coords: Array) {\n const color = layer.paint.get('fill-color');\n const opacity = layer.paint.get('fill-opacity');\n\n if (opacity.constantOr(1) === 0) {\n return;\n }\n\n const colorMode = painter.colorModeForRenderPass();\n\n const pattern = layer.paint.get('fill-pattern');\n const pass = painter.opaquePassEnabledForLayer() &&\n (!pattern.constantOr(1 as any) &&\n color.constantOr(Color.transparent).a === 1 &&\n opacity.constantOr(0) === 1) ? 'opaque' : 'translucent';\n\n // Draw fill\n if (painter.renderPass === pass) {\n const depthMode = painter.depthModeForSublayer(\n 1, painter.renderPass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);\n drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, false);\n }\n\n // Draw stroke\n if (painter.renderPass === 'translucent' && layer.paint.get('fill-antialias')) {\n\n // If we defined a different color for the fill outline, we are\n // going to ignore the bits in 0x07 and just care about the global\n // clipping mask.\n // Otherwise, we only want to drawFill the antialiased parts that are\n // *outside* the current shape. This is important in case the fill\n // or stroke color is translucent. If we wouldn't clip to outside\n // the current shape, some pixels from the outline stroke overlapped\n // the (non-antialiased) fill.\n const depthMode = painter.depthModeForSublayer(\n layer.getPaintProperty('fill-outline-color') ? 2 : 0, DepthMode.ReadOnly);\n drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, true);\n }\n}\n\nfunction drawFillTiles(\n painter: Painter,\n sourceCache: SourceCache,\n layer: FillStyleLayer,\n coords: Array,\n depthMode: Readonly,\n colorMode: Readonly,\n isOutline: boolean) {\n const gl = painter.context.gl;\n const fillPropertyName = 'fill-pattern';\n const patternProperty = layer.paint.get(fillPropertyName);\n const image = patternProperty && patternProperty.constantOr(1 as any);\n const crossfade = layer.getCrossfadeParameters();\n let drawMode, programName, uniformValues, indexBuffer, segments;\n\n if (!isOutline) {\n programName = image ? 'fillPattern' : 'fill';\n drawMode = gl.TRIANGLES;\n } else {\n programName = image && !layer.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline';\n drawMode = gl.LINES;\n }\n\n const constantPattern = patternProperty.constantOr(null);\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n if (image && !tile.patternsLoaded()) continue;\n\n const bucket: FillBucket = (tile.getBucket(layer) as any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram(programName, programConfiguration);\n const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord);\n\n if (image) {\n painter.context.activeTexture.set(gl.TEXTURE0);\n tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n programConfiguration.updatePaintBuffers(crossfade);\n }\n\n updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer);\n\n const terrainCoord = terrainData ? coord : null;\n const posMatrix = terrainCoord ? terrainCoord.posMatrix : coord.posMatrix;\n const tileMatrix = painter.translatePosMatrix(posMatrix, tile,\n layer.paint.get('fill-translate'), layer.paint.get('fill-translate-anchor'));\n\n if (!isOutline) {\n indexBuffer = bucket.indexBuffer;\n segments = bucket.segments;\n uniformValues = image ?\n fillPatternUniformValues(tileMatrix, painter, crossfade, tile) :\n fillUniformValues(tileMatrix);\n } else {\n indexBuffer = bucket.indexBuffer2;\n segments = bucket.segments2;\n const drawingBufferSize = [gl.drawingBufferWidth, gl.drawingBufferHeight] as [number, number];\n uniformValues = (programName === 'fillOutlinePattern' && image) ?\n fillOutlinePatternUniformValues(tileMatrix, painter, crossfade, tile, drawingBufferSize) :\n fillOutlineUniformValues(tileMatrix, drawingBufferSize);\n }\n\n program.draw(painter.context, drawMode, depthMode,\n painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, terrainData,\n layer.id, bucket.layoutVertexBuffer, indexBuffer, segments,\n layer.paint, painter.transform.zoom, programConfiguration);\n }\n}\n","import {DepthMode} from '../gl/depth_mode';\nimport {StencilMode} from '../gl/stencil_mode';\nimport {ColorMode} from '../gl/color_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {\n fillExtrusionUniformValues,\n fillExtrusionPatternUniformValues,\n} from './program/fill_extrusion_program';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {FillExtrusionStyleLayer} from '../style/style_layer/fill_extrusion_style_layer';\nimport type {FillExtrusionBucket} from '../data/bucket/fill_extrusion_bucket';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nimport {updatePatternPositionsInProgram} from './update_pattern_positions_in_program';\n\nexport function drawFillExtrusion(painter: Painter, source: SourceCache, layer: FillExtrusionStyleLayer, coords: Array) {\n const opacity = layer.paint.get('fill-extrusion-opacity');\n if (opacity === 0) {\n return;\n }\n\n if (painter.renderPass === 'translucent') {\n const depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);\n\n if (opacity === 1 && !layer.paint.get('fill-extrusion-pattern').constantOr(1 as any)) {\n const colorMode = painter.colorModeForRenderPass();\n drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode);\n\n } else {\n // Draw transparent buildings in two passes so that only the closest surface is drawn.\n // First draw all the extrusions into only the depth buffer. No colors are drawn.\n drawExtrusionTiles(painter, source, layer, coords, depthMode,\n StencilMode.disabled,\n ColorMode.disabled);\n\n // Then draw all the extrusions a second type, only coloring fragments if they have the\n // same depth value as the closest fragment in the previous pass. Use the stencil buffer\n // to prevent the second draw in cases where we have coincident polygons.\n drawExtrusionTiles(painter, source, layer, coords, depthMode,\n painter.stencilModeFor3D(),\n painter.colorModeForRenderPass());\n }\n }\n}\n\nfunction drawExtrusionTiles(\n painter: Painter,\n source: SourceCache,\n layer: FillExtrusionStyleLayer,\n coords: OverscaledTileID[],\n depthMode: DepthMode,\n stencilMode: Readonly,\n colorMode: Readonly) {\n const context = painter.context;\n const gl = context.gl;\n const fillPropertyName = 'fill-extrusion-pattern';\n const patternProperty = layer.paint.get(fillPropertyName);\n const image = patternProperty.constantOr(1 as any);\n const crossfade = layer.getCrossfadeParameters();\n const opacity = layer.paint.get('fill-extrusion-opacity');\n const constantPattern = patternProperty.constantOr(null);\n for (const coord of coords) {\n const tile = source.getTile(coord);\n const bucket: FillExtrusionBucket = (tile.getBucket(layer) as any);\n if (!bucket) continue;\n\n const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord);\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram(image ? 'fillExtrusionPattern' : 'fillExtrusion', programConfiguration);\n\n if (image) {\n painter.context.activeTexture.set(gl.TEXTURE0);\n tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n programConfiguration.updatePaintBuffers(crossfade);\n }\n\n updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer);\n\n const matrix = painter.translatePosMatrix(\n coord.posMatrix,\n tile,\n layer.paint.get('fill-extrusion-translate'),\n layer.paint.get('fill-extrusion-translate-anchor'));\n\n const shouldUseVerticalGradient = layer.paint.get('fill-extrusion-vertical-gradient');\n const uniformValues = image ?\n fillExtrusionPatternUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) :\n fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity);\n\n program.draw(context, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW,\n uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer,\n bucket.segments, layer.paint, painter.transform.zoom,\n programConfiguration, painter.style.map.terrain && bucket.centroidVertexBuffer);\n }\n}\n","import {Texture} from './texture';\nimport {StencilMode} from '../gl/stencil_mode';\nimport {DepthMode} from '../gl/depth_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {ColorMode} from '../gl/color_mode';\nimport {Tile} from '../source/tile';\nimport {\n hillshadeUniformValues,\n hillshadeUniformPrepareValues\n} from './program/hillshade_program';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {HillshadeStyleLayer} from '../style/style_layer/hillshade_style_layer';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport function drawHillshade(painter: Painter, sourceCache: SourceCache, layer: HillshadeStyleLayer, tileIDs: Array) {\n if (painter.renderPass !== 'offscreen' && painter.renderPass !== 'translucent') return;\n\n const context = painter.context;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n const colorMode = painter.colorModeForRenderPass();\n\n const [stencilModes, coords] = painter.renderPass === 'translucent' ?\n painter.stencilConfigForOverlap(tileIDs) : [{}, tileIDs];\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n if (typeof tile.needsHillshadePrepare !== 'undefined' && tile.needsHillshadePrepare && painter.renderPass === 'offscreen') {\n prepareHillshade(painter, tile, layer, depthMode, StencilMode.disabled, colorMode);\n } else if (painter.renderPass === 'translucent') {\n renderHillshade(painter, coord, tile, layer, depthMode, stencilModes[coord.overscaledZ], colorMode);\n }\n }\n\n context.viewport.set([0, 0, painter.width, painter.height]);\n}\n\nfunction renderHillshade(\n painter: Painter,\n coord: OverscaledTileID,\n tile: Tile,\n layer: HillshadeStyleLayer,\n depthMode: Readonly,\n stencilMode: Readonly,\n colorMode: Readonly) {\n const context = painter.context;\n const gl = context.gl;\n const fbo = tile.fbo;\n if (!fbo) return;\n\n const program = painter.useProgram('hillshade');\n const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord);\n\n context.activeTexture.set(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n\n const terrainCoord = terrainData ? coord : null;\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n hillshadeUniformValues(painter, tile, layer, terrainCoord), terrainData, layer.id, painter.rasterBoundsBuffer,\n painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n\n}\n\n// hillshade rendering is done in two steps. the prepare step first calculates the slope of the terrain in the x and y\n// directions for each pixel, and saves those values to a framebuffer texture in the r and g channels.\nfunction prepareHillshade(\n painter: Painter,\n tile: Tile,\n layer: HillshadeStyleLayer,\n depthMode: Readonly,\n stencilMode: Readonly,\n colorMode: Readonly) {\n const context = painter.context;\n const gl = context.gl;\n const dem = tile.dem;\n if (dem && dem.data) {\n const tileSize = dem.dim;\n const textureStride = dem.stride;\n\n const pixelData = dem.getPixels();\n context.activeTexture.set(gl.TEXTURE1);\n\n context.pixelStoreUnpackPremultiplyAlpha.set(false);\n tile.demTexture = tile.demTexture || painter.getTileTexture(textureStride);\n if (tile.demTexture) {\n const demTexture = tile.demTexture;\n demTexture.update(pixelData, {premultiply: false});\n demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);\n } else {\n tile.demTexture = new Texture(context, pixelData, gl.RGBA, {premultiply: false});\n tile.demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);\n }\n\n context.activeTexture.set(gl.TEXTURE0);\n\n let fbo = tile.fbo;\n\n if (!fbo) {\n const renderTexture = new Texture(context, {width: tileSize, height: tileSize, data: null}, gl.RGBA);\n renderTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n\n fbo = tile.fbo = context.createFramebuffer(tileSize, tileSize, true, false);\n fbo.colorAttachment.set(renderTexture.texture);\n }\n\n context.bindFramebuffer.set(fbo.framebuffer);\n context.viewport.set([0, 0, tileSize, tileSize]);\n\n painter.useProgram('hillshadePrepare').draw(context, gl.TRIANGLES,\n depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n hillshadeUniformPrepareValues(tile.tileID, dem),\n null, layer.id, painter.rasterBoundsBuffer,\n painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n\n tile.needsHillshadePrepare = false;\n }\n}\n","import {clamp} from '../util/util';\n\nimport {ImageSource} from '../source/image_source';\nimport {browser} from '../util/browser';\nimport {StencilMode} from '../gl/stencil_mode';\nimport {DepthMode} from '../gl/depth_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {rasterUniformValues} from './program/raster_program';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {RasterStyleLayer} from '../style/style_layer/raster_style_layer';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport function drawRaster(painter: Painter, sourceCache: SourceCache, layer: RasterStyleLayer, tileIDs: Array) {\n if (painter.renderPass !== 'translucent') return;\n if (layer.paint.get('raster-opacity') === 0) return;\n if (!tileIDs.length) return;\n\n const context = painter.context;\n const gl = context.gl;\n const source = sourceCache.getSource();\n const program = painter.useProgram('raster');\n\n const colorMode = painter.colorModeForRenderPass();\n\n const [stencilModes, coords] = source instanceof ImageSource ? [{}, tileIDs] :\n painter.stencilConfigForOverlap(tileIDs);\n\n const minTileZ = coords[coords.length - 1].overscaledZ;\n\n const align = !painter.options.moving;\n for (const coord of coords) {\n // Set the lower zoom level to sublayer 0, and higher zoom levels to higher sublayers\n // Use gl.LESS to prevent double drawing in areas where tiles overlap.\n const depthMode = painter.depthModeForSublayer(coord.overscaledZ - minTileZ,\n layer.paint.get('raster-opacity') === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS);\n\n const tile = sourceCache.getTile(coord);\n\n tile.registerFadeDuration(layer.paint.get('raster-fade-duration'));\n\n const parentTile = sourceCache.findLoadedParent(coord, 0);\n const siblingTile = sourceCache.findLoadedSibling(coord);\n // Prefer parent tile if present\n const fadeTileReference = parentTile || siblingTile || null;\n const fade = getFadeValues(tile, fadeTileReference, sourceCache, layer, painter.transform, painter.style.map.terrain);\n\n let parentScaleBy, parentTL;\n\n const textureFilter = layer.paint.get('raster-resampling') === 'nearest' ? gl.NEAREST : gl.LINEAR;\n\n context.activeTexture.set(gl.TEXTURE0);\n tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n\n context.activeTexture.set(gl.TEXTURE1);\n\n if (parentTile) {\n parentTile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ);\n parentTL = [tile.tileID.canonical.x * parentScaleBy % 1, tile.tileID.canonical.y * parentScaleBy % 1];\n\n } else {\n tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n }\n\n // Enable anisotropic filtering only when the pitch is greater than 20 degrees\n // to preserve image sharpness on flat or slightly tilted maps.\n if (tile.texture.useMipmap && context.extTextureFilterAnisotropic && painter.transform.pitch > 20) {\n gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,\n context.extTextureFilterAnisotropicMax);\n }\n\n const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord);\n const terrainCoord = terrainData ? coord : null;\n const posMatrix = terrainCoord ? terrainCoord.posMatrix : painter.transform.calculatePosMatrix(coord.toUnwrapped(), align);\n const uniformValues = rasterUniformValues(posMatrix, parentTL || [0, 0], parentScaleBy || 1, fade, layer);\n\n if (source instanceof ImageSource) {\n program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled,\n uniformValues, terrainData, layer.id, source.boundsBuffer,\n painter.quadTriangleIndexBuffer, source.boundsSegments);\n } else {\n program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.disabled,\n uniformValues, terrainData, layer.id, painter.rasterBoundsBuffer,\n painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n }\n }\n}\n\nfunction getFadeValues(tile, parentTile, sourceCache, layer, transform, terrain) {\n const fadeDuration = layer.paint.get('raster-fade-duration');\n\n if (!terrain && fadeDuration > 0) {\n const now = browser.now();\n const sinceTile = (now - tile.timeAdded) / fadeDuration;\n const sinceParent = parentTile ? (now - parentTile.timeAdded) / fadeDuration : -1;\n\n const source = sourceCache.getSource();\n const idealZ = transform.coveringZoomLevel({\n tileSize: source.tileSize,\n roundZoom: source.roundZoom\n });\n\n // if no parent or parent is older, fade in; if parent is younger, fade out\n const fadeIn = !parentTile || Math.abs(parentTile.tileID.overscaledZ - idealZ) > Math.abs(tile.tileID.overscaledZ - idealZ);\n\n const childOpacity = (fadeIn && tile.refreshedUponExpiration) ? 1 : clamp(fadeIn ? sinceTile : 1 - sinceParent, 0, 1);\n\n // we don't crossfade tiles that were just refreshed upon expiring:\n // once they're old enough to pass the crossfading threshold\n // (fadeDuration), unset the `refreshedUponExpiration` flag so we don't\n // incorrectly fail to crossfade them when zooming\n if (tile.refreshedUponExpiration && sinceTile >= 1) tile.refreshedUponExpiration = false;\n\n if (parentTile) {\n return {\n opacity: 1,\n mix: 1 - childOpacity\n };\n } else {\n return {\n opacity: childOpacity,\n mix: 0\n };\n }\n } else {\n return {\n opacity: 1,\n mix: 0\n };\n }\n}\n","import {DepthMode} from '../gl/depth_mode';\nimport {StencilMode} from '../gl/stencil_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {debugUniformValues} from './program/debug_program';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {ColorMode} from '../gl/color_mode';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport {Style} from '../style/style';\n\nconst topColor = new Color(1, 0, 0, 1);\nconst btmColor = new Color(0, 1, 0, 1);\nconst leftColor = new Color(0, 0, 1, 1);\nconst rightColor = new Color(1, 0, 1, 1);\nconst centerColor = new Color(0, 1, 1, 1);\n\nexport function drawDebugPadding(painter: Painter) {\n const padding = painter.transform.padding;\n const lineWidth = 3;\n // Top\n drawHorizontalLine(painter, painter.transform.height - (padding.top || 0), lineWidth, topColor);\n // Bottom\n drawHorizontalLine(painter, padding.bottom || 0, lineWidth, btmColor);\n // Left\n drawVerticalLine(painter, padding.left || 0, lineWidth, leftColor);\n // Right\n drawVerticalLine(painter, painter.transform.width - (padding.right || 0), lineWidth, rightColor);\n // Center\n const center = painter.transform.centerPoint;\n drawCrosshair(painter, center.x, painter.transform.height - center.y, centerColor);\n}\n\nfunction drawCrosshair(painter: Painter, x: number, y: number, color: Color) {\n const size = 20;\n const lineWidth = 2;\n //Vertical line\n drawDebugSSRect(painter, x - lineWidth / 2, y - size / 2, lineWidth, size, color);\n //Horizontal line\n drawDebugSSRect(painter, x - size / 2, y - lineWidth / 2, size, lineWidth, color);\n}\n\nfunction drawHorizontalLine(painter: Painter, y: number, lineWidth: number, color: Color) {\n drawDebugSSRect(painter, 0, y + lineWidth / 2, painter.transform.width, lineWidth, color);\n}\n\nfunction drawVerticalLine(painter: Painter, x: number, lineWidth: number, color: Color) {\n drawDebugSSRect(painter, x - lineWidth / 2, 0, lineWidth, painter.transform.height, color);\n}\n\nfunction drawDebugSSRect(painter: Painter, x: number, y: number, width: number, height: number, color: Color) {\n const context = painter.context;\n const gl = context.gl;\n\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(x * painter.pixelRatio, y * painter.pixelRatio, width * painter.pixelRatio, height * painter.pixelRatio);\n context.clear({color});\n gl.disable(gl.SCISSOR_TEST);\n}\n\nexport function drawDebug(painter: Painter, sourceCache: SourceCache, coords: Array) {\n for (let i = 0; i < coords.length; i++) {\n drawDebugTile(painter, sourceCache, coords[i]);\n }\n}\n\nfunction drawDebugTile(painter: Painter, sourceCache: SourceCache, coord: OverscaledTileID) {\n const context = painter.context;\n const gl = context.gl;\n\n const posMatrix = coord.posMatrix;\n const program = painter.useProgram('debug');\n\n const depthMode = DepthMode.disabled;\n const stencilMode = StencilMode.disabled;\n const colorMode = painter.colorModeForRenderPass();\n const id = '$debug';\n const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord);\n\n context.activeTexture.set(gl.TEXTURE0);\n\n const tileRawData = sourceCache.getTileByID(coord.key).latestRawTileData;\n const tileByteLength = (tileRawData && tileRawData.byteLength) || 0;\n const tileSizeKb = Math.floor(tileByteLength / 1024);\n const tileSize = sourceCache.getTile(coord).tileSize;\n const scaleRatio = (512 / Math.min(tileSize, 512) * (coord.overscaledZ / painter.transform.zoom)) * 0.5;\n let tileIdText = coord.canonical.toString();\n if (coord.overscaledZ !== coord.canonical.z) {\n tileIdText += ` => ${coord.overscaledZ}`;\n }\n const tileLabel = `${tileIdText} ${tileSizeKb}kB`;\n drawTextToOverlay(painter, tileLabel);\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled,\n debugUniformValues(posMatrix, Color.transparent, scaleRatio), null, id,\n painter.debugBuffer, painter.quadTriangleIndexBuffer, painter.debugSegments);\n program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n debugUniformValues(posMatrix, Color.red), terrainData, id,\n painter.debugBuffer, painter.tileBorderIndexBuffer, painter.debugSegments);\n}\n\nfunction drawTextToOverlay(painter: Painter, text: string) {\n painter.initDebugOverlayCanvas();\n const canvas = painter.debugOverlayCanvas;\n const gl = painter.context.gl;\n const ctx2d = painter.debugOverlayCanvas.getContext('2d');\n ctx2d.clearRect(0, 0, canvas.width, canvas.height);\n\n ctx2d.shadowColor = 'white';\n ctx2d.shadowBlur = 2;\n ctx2d.lineWidth = 1.5;\n ctx2d.strokeStyle = 'white';\n ctx2d.textBaseline = 'top';\n ctx2d.font = `bold ${36}px Open Sans, sans-serif`;\n ctx2d.fillText(text, 5, 5);\n ctx2d.strokeText(text, 5, 5);\n\n painter.debugOverlayTexture.update(canvas);\n painter.debugOverlayTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n}\n\nexport function selectDebugSource(style: Style, zoom: number): SourceCache | null {\n // Use vector source with highest maxzoom\n // Else use source with highest maxzoom of any type\n let selectedSource: SourceCache = null;\n const layers = Object.values(style._layers);\n const sources = layers.flatMap((layer) => {\n if (layer.source && !layer.isHidden(zoom)) {\n const sourceCache = style.sourceCaches[layer.source];\n return [sourceCache];\n } else {\n return [];\n }\n });\n const vectorSources = sources.filter((source) => source.getSource().type === 'vector');\n const otherSources = sources.filter((source) => source.getSource().type !== 'vector');\n const considerSource = (source: SourceCache) => {\n if (!selectedSource || (selectedSource.getSource().maxzoom < source.getSource().maxzoom)) {\n selectedSource = source;\n }\n };\n vectorSources.forEach((source) => considerSource(source));\n if (!selectedSource) {\n otherSources.forEach((source) => considerSource(source));\n }\n return selectedSource;\n}\n","import {StencilMode} from '../gl/stencil_mode';\nimport {DepthMode} from '../gl/depth_mode';\nimport {terrainUniformValues, terrainDepthUniformValues, terrainCoordsUniformValues} from './program/terrain_program';\nimport type {Painter} from './painter';\nimport type {Tile} from '../source/tile';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {ColorMode} from '../gl/color_mode';\nimport {Terrain} from './terrain';\n\n/**\n * Redraw the Depth Framebuffer\n * @param painter - the painter\n * @param terrain - the terrain\n */\nfunction drawDepth(painter: Painter, terrain: Terrain) {\n const context = painter.context;\n const gl = context.gl;\n const colorMode = ColorMode.unblended;\n const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);\n const mesh = terrain.getTerrainMesh();\n const tiles = terrain.sourceCache.getRenderableTiles();\n const program = painter.useProgram('terrainDepth');\n context.bindFramebuffer.set(terrain.getFramebuffer('depth').framebuffer);\n context.viewport.set([0, 0, painter.width / devicePixelRatio, painter.height / devicePixelRatio]);\n context.clear({color: Color.transparent, depth: 1});\n for (const tile of tiles) {\n const terrainData = terrain.getTerrainData(tile.tileID);\n const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped());\n const uniformValues = terrainDepthUniformValues(posMatrix, terrain.getMeshFrameDelta(painter.transform.zoom));\n program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n }\n context.bindFramebuffer.set(null);\n context.viewport.set([0, 0, painter.width, painter.height]);\n}\n\n/**\n * Redraw the Coords Framebuffers\n * @param painter - the painter\n * @param terrain - the terrain\n */\nfunction drawCoords(painter: Painter, terrain: Terrain) {\n const context = painter.context;\n const gl = context.gl;\n const colorMode = ColorMode.unblended;\n const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);\n const mesh = terrain.getTerrainMesh();\n const coords = terrain.getCoordsTexture();\n const tiles = terrain.sourceCache.getRenderableTiles();\n\n // draw tile-coords into framebuffer\n const program = painter.useProgram('terrainCoords');\n context.bindFramebuffer.set(terrain.getFramebuffer('coords').framebuffer);\n context.viewport.set([0, 0, painter.width / devicePixelRatio, painter.height / devicePixelRatio]);\n context.clear({color: Color.transparent, depth: 1});\n terrain.coordsIndex = [];\n for (const tile of tiles) {\n const terrainData = terrain.getTerrainData(tile.tileID);\n context.activeTexture.set(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, coords.texture);\n const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped());\n const uniformValues = terrainCoordsUniformValues(posMatrix, 255 - terrain.coordsIndex.length, terrain.getMeshFrameDelta(painter.transform.zoom));\n program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n terrain.coordsIndex.push(tile.tileID.key);\n }\n context.bindFramebuffer.set(null);\n context.viewport.set([0, 0, painter.width, painter.height]);\n}\n\nfunction drawTerrain(painter: Painter, terrain: Terrain, tiles: Array) {\n const context = painter.context;\n const gl = context.gl;\n const colorMode = painter.colorModeForRenderPass();\n const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);\n const program = painter.useProgram('terrain');\n const mesh = terrain.getTerrainMesh();\n\n context.bindFramebuffer.set(null);\n context.viewport.set([0, 0, painter.width, painter.height]);\n\n for (const tile of tiles) {\n const texture = painter.renderToTexture.getTexture(tile);\n const terrainData = terrain.getTerrainData(tile.tileID);\n context.activeTexture.set(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, texture.texture);\n const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped());\n const eleDelta = terrain.getMeshFrameDelta(painter.transform.zoom);\n const fogMatrix = painter.transform.calculateFogMatrix(tile.tileID.toUnwrapped());\n const uniformValues = terrainUniformValues(posMatrix, eleDelta, fogMatrix, painter.style.sky, painter.transform.pitch);\n program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n }\n\n}\n\nexport {\n drawTerrain,\n drawDepth,\n drawCoords\n};\n","import {SegmentVector} from '../data/segment';\nimport {VertexBuffer} from '../gl/vertex_buffer';\nimport {IndexBuffer} from '../gl/index_buffer';\n\nexport class Mesh {\n vertexBuffer: VertexBuffer;\n indexBuffer: IndexBuffer;\n segments: SegmentVector;\n\n constructor(vertexBuffer: VertexBuffer, indexBuffer: IndexBuffer, segments: SegmentVector) {\n this.vertexBuffer = vertexBuffer;\n this.indexBuffer = indexBuffer;\n this.segments = segments;\n }\n\n destroy(): void {\n this.vertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.segments.destroy();\n\n this.vertexBuffer = null;\n this.indexBuffer = null;\n this.segments = null;\n }\n}\n","import {browser} from '../util/browser';\nimport {mat4, vec3} from 'gl-matrix';\nimport {SourceCache} from '../source/source_cache';\nimport {EXTENT} from '../data/extent';\nimport {pixelsToTileUnits} from '../source/pixels_to_tile_units';\nimport {SegmentVector} from '../data/segment';\nimport {RasterBoundsArray, PosArray, TriangleIndexArray, LineStripIndexArray} from '../data/array_types.g';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport posAttributes from '../data/pos_attributes';\nimport {ProgramConfiguration} from '../data/program_configuration';\nimport {CrossTileSymbolIndex} from '../symbol/cross_tile_symbol_index';\nimport {shaders} from '../shaders/shaders';\nimport {Program} from './program';\nimport {programUniforms} from './program/program_uniforms';\nimport {Context} from '../gl/context';\nimport {DepthMode} from '../gl/depth_mode';\nimport {StencilMode} from '../gl/stencil_mode';\nimport {ColorMode} from '../gl/color_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {Texture} from './texture';\nimport {clippingMaskUniformValues} from './program/clipping_mask_program';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {drawSymbols} from './draw_symbol';\nimport {drawCircles} from './draw_circle';\nimport {drawHeatmap} from './draw_heatmap';\nimport {drawLine} from './draw_line';\nimport {drawFill} from './draw_fill';\nimport {drawFillExtrusion} from './draw_fill_extrusion';\nimport {drawHillshade} from './draw_hillshade';\nimport {drawRaster} from './draw_raster';\nimport {drawBackground} from './draw_background';\nimport {drawDebug, drawDebugPadding, selectDebugSource} from './draw_debug';\nimport {drawCustom} from './draw_custom';\nimport {drawDepth, drawCoords} from './draw_terrain';\nimport {OverscaledTileID} from '../source/tile_id';\nimport {RenderToTexture} from './render_to_texture';\nimport {drawSky} from './draw_sky';\n\nimport type {Transform} from '../geo/transform';\nimport type {Tile} from '../source/tile';\nimport type {Style} from '../style/style';\nimport type {StyleLayer} from '../style/style_layer';\nimport type {CrossFaded} from '../style/properties';\nimport type {LineAtlas} from './line_atlas';\nimport type {ImageManager} from './image_manager';\nimport type {GlyphManager} from './glyph_manager';\nimport type {VertexBuffer} from '../gl/vertex_buffer';\nimport type {IndexBuffer} from '../gl/index_buffer';\nimport type {DepthRangeType, DepthMaskType, DepthFuncType} from '../gl/types';\nimport type {ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\n\nexport type RenderPass = 'offscreen' | 'opaque' | 'translucent';\n\ntype PainterOptions = {\n showOverdrawInspector: boolean;\n showTileBoundaries: boolean;\n showPadding: boolean;\n rotating: boolean;\n zooming: boolean;\n moving: boolean;\n fadeDuration: number;\n};\n\n/**\n * @internal\n * Initialize a new painter object.\n */\nexport class Painter {\n context: Context;\n transform: Transform;\n renderToTexture: RenderToTexture;\n _tileTextures: {\n [_: number]: Array;\n };\n numSublayers: number;\n depthEpsilon: number;\n emptyProgramConfiguration: ProgramConfiguration;\n width: number;\n height: number;\n pixelRatio: number;\n tileExtentBuffer: VertexBuffer;\n tileExtentSegments: SegmentVector;\n debugBuffer: VertexBuffer;\n debugSegments: SegmentVector;\n rasterBoundsBuffer: VertexBuffer;\n rasterBoundsSegments: SegmentVector;\n viewportBuffer: VertexBuffer;\n viewportSegments: SegmentVector;\n quadTriangleIndexBuffer: IndexBuffer;\n tileBorderIndexBuffer: IndexBuffer;\n _tileClippingMaskIDs: {[_: string]: number};\n stencilClearMode: StencilMode;\n style: Style;\n options: PainterOptions;\n lineAtlas: LineAtlas;\n imageManager: ImageManager;\n glyphManager: GlyphManager;\n depthRangeFor3D: DepthRangeType;\n opaquePassCutoff: number;\n renderPass: RenderPass;\n currentLayer: number;\n currentStencilSource: string;\n nextStencilID: number;\n id: string;\n _showOverdrawInspector: boolean;\n cache: {[_: string]: Program};\n crossTileSymbolIndex: CrossTileSymbolIndex;\n symbolFadeChange: number;\n debugOverlayTexture: Texture;\n debugOverlayCanvas: HTMLCanvasElement;\n // this object stores the current camera-matrix and the last render time\n // of the terrain-facilitators. e.g. depth & coords framebuffers\n // every time the camera-matrix changes the terrain-facilitators will be redrawn.\n terrainFacilitator: {dirty: boolean; matrix: mat4; renderTime: number};\n\n constructor(gl: WebGLRenderingContext | WebGL2RenderingContext, transform: Transform) {\n this.context = new Context(gl);\n this.transform = transform;\n this._tileTextures = {};\n this.terrainFacilitator = {dirty: true, matrix: mat4.identity(new Float64Array(16) as any), renderTime: 0};\n\n this.setup();\n\n // Within each layer there are multiple distinct z-planes that can be drawn to.\n // This is implemented using the WebGL depth buffer.\n this.numSublayers = SourceCache.maxUnderzooming + SourceCache.maxOverzooming + 1;\n this.depthEpsilon = 1 / Math.pow(2, 16);\n\n this.crossTileSymbolIndex = new CrossTileSymbolIndex();\n }\n\n /*\n * Update the GL viewport, projection matrix, and transforms to compensate\n * for a new width and height value.\n */\n resize(width: number, height: number, pixelRatio: number) {\n this.width = Math.floor(width * pixelRatio);\n this.height = Math.floor(height * pixelRatio);\n this.pixelRatio = pixelRatio;\n this.context.viewport.set([0, 0, this.width, this.height]);\n\n if (this.style) {\n for (const layerId of this.style._order) {\n this.style._layers[layerId].resize();\n }\n }\n }\n\n setup() {\n const context = this.context;\n\n const tileExtentArray = new PosArray();\n tileExtentArray.emplaceBack(0, 0);\n tileExtentArray.emplaceBack(EXTENT, 0);\n tileExtentArray.emplaceBack(0, EXTENT);\n tileExtentArray.emplaceBack(EXTENT, EXTENT);\n this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);\n this.tileExtentSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n const debugArray = new PosArray();\n debugArray.emplaceBack(0, 0);\n debugArray.emplaceBack(EXTENT, 0);\n debugArray.emplaceBack(0, EXTENT);\n debugArray.emplaceBack(EXTENT, EXTENT);\n this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members);\n this.debugSegments = SegmentVector.simpleSegment(0, 0, 4, 5);\n\n const rasterBoundsArray = new RasterBoundsArray();\n rasterBoundsArray.emplaceBack(0, 0, 0, 0);\n rasterBoundsArray.emplaceBack(EXTENT, 0, EXTENT, 0);\n rasterBoundsArray.emplaceBack(0, EXTENT, 0, EXTENT);\n rasterBoundsArray.emplaceBack(EXTENT, EXTENT, EXTENT, EXTENT);\n this.rasterBoundsBuffer = context.createVertexBuffer(rasterBoundsArray, rasterBoundsAttributes.members);\n this.rasterBoundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n const viewportArray = new PosArray();\n viewportArray.emplaceBack(0, 0);\n viewportArray.emplaceBack(1, 0);\n viewportArray.emplaceBack(0, 1);\n viewportArray.emplaceBack(1, 1);\n this.viewportBuffer = context.createVertexBuffer(viewportArray, posAttributes.members);\n this.viewportSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n const tileLineStripIndices = new LineStripIndexArray();\n tileLineStripIndices.emplaceBack(0);\n tileLineStripIndices.emplaceBack(1);\n tileLineStripIndices.emplaceBack(3);\n tileLineStripIndices.emplaceBack(2);\n tileLineStripIndices.emplaceBack(0);\n this.tileBorderIndexBuffer = context.createIndexBuffer(tileLineStripIndices);\n\n const quadTriangleIndices = new TriangleIndexArray();\n quadTriangleIndices.emplaceBack(0, 1, 2);\n quadTriangleIndices.emplaceBack(2, 1, 3);\n this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);\n\n const gl = this.context.gl;\n this.stencilClearMode = new StencilMode({func: gl.ALWAYS, mask: 0}, 0x0, 0xFF, gl.ZERO, gl.ZERO, gl.ZERO);\n }\n\n /*\n * Reset the drawing canvas by clearing the stencil buffer so that we can draw\n * new tiles at the same location, while retaining previously drawn pixels.\n */\n clearStencil() {\n const context = this.context;\n const gl = context.gl;\n\n this.nextStencilID = 1;\n this.currentStencilSource = undefined;\n\n // As a temporary workaround for https://github.com/mapbox/mapbox-gl-js/issues/5490,\n // pending an upstream fix, we draw a fullscreen stencil=0 clipping mask here,\n // effectively clearing the stencil buffer: once an upstream patch lands, remove\n // this function in favor of context.clear({ stencil: 0x0 })\n\n const matrix = mat4.create();\n mat4.ortho(matrix, 0, this.width, this.height, 0, 0, 1);\n mat4.scale(matrix, matrix, [gl.drawingBufferWidth, gl.drawingBufferHeight, 0]);\n\n this.useProgram('clippingMask').draw(context, gl.TRIANGLES,\n DepthMode.disabled, this.stencilClearMode, ColorMode.disabled, CullFaceMode.disabled,\n clippingMaskUniformValues(matrix), null,\n '$clipping', this.viewportBuffer,\n this.quadTriangleIndexBuffer, this.viewportSegments);\n }\n\n _renderTileClippingMasks(layer: StyleLayer, tileIDs: Array) {\n if (this.currentStencilSource === layer.source || !layer.isTileClipped() || !tileIDs || !tileIDs.length) return;\n\n this.currentStencilSource = layer.source;\n\n const context = this.context;\n const gl = context.gl;\n\n if (this.nextStencilID + tileIDs.length > 256) {\n // we'll run out of fresh IDs so we need to clear and start from scratch\n this.clearStencil();\n }\n\n context.setColorMode(ColorMode.disabled);\n context.setDepthMode(DepthMode.disabled);\n\n const program = this.useProgram('clippingMask');\n\n this._tileClippingMaskIDs = {};\n\n for (const tileID of tileIDs) {\n const id = this._tileClippingMaskIDs[tileID.key] = this.nextStencilID++;\n const terrainData = this.style.map.terrain && this.style.map.terrain.getTerrainData(tileID);\n\n program.draw(context, gl.TRIANGLES, DepthMode.disabled,\n // Tests will always pass, and ref value will be written to stencil buffer.\n new StencilMode({func: gl.ALWAYS, mask: 0}, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE),\n ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(tileID.posMatrix),\n terrainData, '$clipping', this.tileExtentBuffer,\n this.quadTriangleIndexBuffer, this.tileExtentSegments);\n }\n }\n\n stencilModeFor3D(): StencilMode {\n this.currentStencilSource = undefined;\n\n if (this.nextStencilID + 1 > 256) {\n this.clearStencil();\n }\n\n const id = this.nextStencilID++;\n const gl = this.context.gl;\n return new StencilMode({func: gl.NOTEQUAL, mask: 0xFF}, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);\n }\n\n stencilModeForClipping(tileID: OverscaledTileID): StencilMode {\n const gl = this.context.gl;\n return new StencilMode({func: gl.EQUAL, mask: 0xFF}, this._tileClippingMaskIDs[tileID.key], 0x00, gl.KEEP, gl.KEEP, gl.REPLACE);\n }\n\n /*\n * Sort coordinates by Z as drawing tiles is done in Z-descending order.\n * All children with the same Z write the same stencil value. Children\n * stencil values are greater than parent's. This is used only for raster\n * and raster-dem tiles, which are already clipped to tile boundaries, to\n * mask area of tile overlapped by children tiles.\n * Stencil ref values continue range used in _tileClippingMaskIDs.\n *\n * Returns [StencilMode for tile overscaleZ map, sortedCoords].\n */\n stencilConfigForOverlap(tileIDs: Array): [{\n [_: number]: Readonly;\n }, Array] {\n const gl = this.context.gl;\n const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ);\n const minTileZ = coords[coords.length - 1].overscaledZ;\n const stencilValues = coords[0].overscaledZ - minTileZ + 1;\n if (stencilValues > 1) {\n this.currentStencilSource = undefined;\n if (this.nextStencilID + stencilValues > 256) {\n this.clearStencil();\n }\n const zToStencilMode = {};\n for (let i = 0; i < stencilValues; i++) {\n zToStencilMode[i + minTileZ] = new StencilMode({func: gl.GEQUAL, mask: 0xFF}, i + this.nextStencilID, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);\n }\n this.nextStencilID += stencilValues;\n return [zToStencilMode, coords];\n }\n return [{[minTileZ]: StencilMode.disabled}, coords];\n }\n\n colorModeForRenderPass(): Readonly {\n const gl = this.context.gl;\n if (this._showOverdrawInspector) {\n const numOverdrawSteps = 8;\n const a = 1 / numOverdrawSteps;\n\n return new ColorMode([gl.CONSTANT_COLOR, gl.ONE], new Color(a, a, a, 0), [true, true, true, true]);\n } else if (this.renderPass === 'opaque') {\n return ColorMode.unblended;\n } else {\n return ColorMode.alphaBlended;\n }\n }\n\n depthModeForSublayer(n: number, mask: DepthMaskType, func?: DepthFuncType | null): Readonly {\n if (!this.opaquePassEnabledForLayer()) return DepthMode.disabled;\n const depth = 1 - ((1 + this.currentLayer) * this.numSublayers + n) * this.depthEpsilon;\n return new DepthMode(func || this.context.gl.LEQUAL, mask, [depth, depth]);\n }\n\n /*\n * The opaque pass and 3D layers both use the depth buffer.\n * Layers drawn above 3D layers need to be drawn using the\n * painter's algorithm so that they appear above 3D features.\n * This returns true for layers that can be drawn using the\n * opaque pass.\n */\n opaquePassEnabledForLayer() {\n return this.currentLayer < this.opaquePassCutoff;\n }\n\n render(style: Style, options: PainterOptions) {\n this.style = style;\n this.options = options;\n\n this.lineAtlas = style.lineAtlas;\n this.imageManager = style.imageManager;\n this.glyphManager = style.glyphManager;\n\n this.symbolFadeChange = style.placement.symbolFadeChange(browser.now());\n\n this.imageManager.beginFrame();\n\n const layerIds = this.style._order;\n const sourceCaches = this.style.sourceCaches;\n\n const coordsAscending: {[_: string]: Array} = {};\n const coordsDescending: {[_: string]: Array} = {};\n const coordsDescendingSymbol: {[_: string]: Array} = {};\n\n for (const id in sourceCaches) {\n const sourceCache = sourceCaches[id];\n if (sourceCache.used) {\n sourceCache.prepare(this.context);\n }\n\n coordsAscending[id] = sourceCache.getVisibleCoordinates();\n coordsDescending[id] = coordsAscending[id].slice().reverse();\n coordsDescendingSymbol[id] = sourceCache.getVisibleCoordinates(true).reverse();\n }\n\n this.opaquePassCutoff = Infinity;\n for (let i = 0; i < layerIds.length; i++) {\n const layerId = layerIds[i];\n if (this.style._layers[layerId].is3D()) {\n this.opaquePassCutoff = i;\n break;\n }\n }\n\n this.maybeDrawDepthAndCoords(false);\n\n if (this.renderToTexture) {\n this.renderToTexture.prepareForRender(this.style, this.transform.zoom);\n // this is disabled, because render-to-texture is rendering all layers from bottom to top.\n this.opaquePassCutoff = 0;\n }\n\n // Offscreen pass ===============================================\n // We first do all rendering that requires rendering to a separate\n // framebuffer, and then save those for rendering back to the map\n // later: in doing this we avoid doing expensive framebuffer restores.\n this.renderPass = 'offscreen';\n\n for (const layerId of layerIds) {\n const layer = this.style._layers[layerId];\n if (!layer.hasOffscreenPass() || layer.isHidden(this.transform.zoom)) continue;\n\n const coords = coordsDescending[layer.source];\n if (layer.type !== 'custom' && !coords.length) continue;\n\n this.renderLayer(this, sourceCaches[layer.source], layer, coords);\n }\n\n // Rebind the main framebuffer now that all offscreen layers have been rendered:\n this.context.bindFramebuffer.set(null);\n\n // Clear buffers in preparation for drawing to the main framebuffer\n this.context.clear({color: options.showOverdrawInspector ? Color.black : Color.transparent, depth: 1});\n this.clearStencil();\n\n // draw sky first to not overwrite symbols\n if (this.style.sky) drawSky(this, this.style.sky);\n\n this._showOverdrawInspector = options.showOverdrawInspector;\n this.depthRangeFor3D = [0, 1 - ((style._order.length + 2) * this.numSublayers * this.depthEpsilon)];\n\n // Opaque pass ===============================================\n // Draw opaque layers top-to-bottom first.\n if (!this.renderToTexture) {\n this.renderPass = 'opaque';\n\n for (this.currentLayer = layerIds.length - 1; this.currentLayer >= 0; this.currentLayer--) {\n const layer = this.style._layers[layerIds[this.currentLayer]];\n const sourceCache = sourceCaches[layer.source];\n const coords = coordsAscending[layer.source];\n\n this._renderTileClippingMasks(layer, coords);\n this.renderLayer(this, sourceCache, layer, coords);\n }\n }\n\n // Translucent pass ===============================================\n // Draw all other layers bottom-to-top.\n this.renderPass = 'translucent';\n\n for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) {\n const layer = this.style._layers[layerIds[this.currentLayer]];\n const sourceCache = sourceCaches[layer.source];\n\n if (this.renderToTexture && this.renderToTexture.renderLayer(layer)) continue;\n\n // For symbol layers in the translucent pass, we add extra tiles to the renderable set\n // for cross-tile symbol fading. Symbol layers don't use tile clipping, so no need to render\n // separate clipping masks\n const coords = (layer.type === 'symbol' ? coordsDescendingSymbol : coordsDescending)[layer.source];\n\n this._renderTileClippingMasks(layer, coordsAscending[layer.source]);\n this.renderLayer(this, sourceCache, layer, coords);\n }\n\n if (this.options.showTileBoundaries) {\n const selectedSource = selectDebugSource(this.style, this.transform.zoom);\n if (selectedSource) {\n drawDebug(this, selectedSource, selectedSource.getVisibleCoordinates());\n }\n }\n\n if (this.options.showPadding) {\n drawDebugPadding(this);\n }\n\n // Set defaults for most GL values so that anyone using the state after the render\n // encounters more expected values.\n this.context.setDefault();\n }\n\n /**\n * Update the depth and coords framebuffers, if the contents of those frame buffers is out of date.\n * If requireExact is false, then the contents of those frame buffers is not updated if it is close\n * to accurate (that is, the camera has not moved much since it was updated last).\n */\n maybeDrawDepthAndCoords(requireExact: boolean) {\n if (!this.style || !this.style.map || !this.style.map.terrain) {\n return;\n }\n const prevMatrix = this.terrainFacilitator.matrix;\n const currMatrix = this.transform.modelViewProjectionMatrix;\n\n // Update coords/depth-framebuffer on camera movement, or tile reloading\n let doUpdate = this.terrainFacilitator.dirty;\n doUpdate ||= requireExact ? !mat4.exactEquals(prevMatrix, currMatrix) : !mat4.equals(prevMatrix, currMatrix);\n doUpdate ||= this.style.map.terrain.sourceCache.tilesAfterTime(this.terrainFacilitator.renderTime).length > 0;\n\n if (!doUpdate) {\n return;\n }\n\n mat4.copy(prevMatrix, currMatrix);\n this.terrainFacilitator.renderTime = Date.now();\n this.terrainFacilitator.dirty = false;\n drawDepth(this, this.style.map.terrain);\n drawCoords(this, this.style.map.terrain);\n }\n\n renderLayer(painter: Painter, sourceCache: SourceCache, layer: StyleLayer, coords: Array) {\n if (layer.isHidden(this.transform.zoom)) return;\n if (layer.type !== 'background' && layer.type !== 'custom' && !(coords || []).length) return;\n this.id = layer.id;\n\n switch (layer.type) {\n case 'symbol':\n drawSymbols(painter, sourceCache, layer as any, coords, this.style.placement.variableOffsets);\n break;\n case 'circle':\n drawCircles(painter, sourceCache, layer as any, coords);\n break;\n case 'heatmap':\n drawHeatmap(painter, sourceCache, layer as any, coords);\n break;\n case 'line':\n drawLine(painter, sourceCache, layer as any, coords);\n break;\n case 'fill':\n drawFill(painter, sourceCache, layer as any, coords);\n break;\n case 'fill-extrusion':\n drawFillExtrusion(painter, sourceCache, layer as any, coords);\n break;\n case 'hillshade':\n drawHillshade(painter, sourceCache, layer as any, coords);\n break;\n case 'raster':\n drawRaster(painter, sourceCache, layer as any, coords);\n break;\n case 'background':\n drawBackground(painter, sourceCache, layer as any, coords);\n break;\n case 'custom':\n drawCustom(painter, sourceCache, layer as any);\n break;\n }\n }\n\n /**\n * Transform a matrix to incorporate the *-translate and *-translate-anchor properties into it.\n * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units.\n * @returns matrix\n */\n translatePosMatrix(matrix: mat4, tile: Tile, translate: [number, number], translateAnchor: 'map' | 'viewport', inViewportPixelUnitsUnits?: boolean): mat4 {\n if (!translate[0] && !translate[1]) return matrix;\n\n const angle = inViewportPixelUnitsUnits ?\n (translateAnchor === 'map' ? this.transform.angle : 0) :\n (translateAnchor === 'viewport' ? -this.transform.angle : 0);\n\n if (angle) {\n const sinA = Math.sin(angle);\n const cosA = Math.cos(angle);\n translate = [\n translate[0] * cosA - translate[1] * sinA,\n translate[0] * sinA + translate[1] * cosA\n ];\n }\n\n const translation = [\n inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], this.transform.zoom),\n inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], this.transform.zoom),\n 0\n ] as vec3;\n\n const translatedMatrix = new Float32Array(16);\n mat4.translate(translatedMatrix, matrix, translation);\n return translatedMatrix;\n }\n\n saveTileTexture(texture: Texture) {\n const textures = this._tileTextures[texture.size[0]];\n if (!textures) {\n this._tileTextures[texture.size[0]] = [texture];\n } else {\n textures.push(texture);\n }\n }\n\n getTileTexture(size: number) {\n const textures = this._tileTextures[size];\n return textures && textures.length > 0 ? textures.pop() : null;\n }\n\n /**\n * Checks whether a pattern image is needed, and if it is, whether it is not loaded.\n *\n * @returns true if a needed image is missing and rendering needs to be skipped.\n */\n isPatternMissing(image?: CrossFaded | null): boolean {\n if (!image) return false;\n if (!image.from || !image.to) return true;\n const imagePosA = this.imageManager.getPattern(image.from.toString());\n const imagePosB = this.imageManager.getPattern(image.to.toString());\n return !imagePosA || !imagePosB;\n }\n\n useProgram(name: string, programConfiguration?: ProgramConfiguration | null): Program {\n this.cache = this.cache || {};\n const key = name +\n (programConfiguration ? programConfiguration.cacheKey : '') +\n (this._showOverdrawInspector ? '/overdraw' : '') +\n (this.style.map.terrain ? '/terrain' : '');\n if (!this.cache[key]) {\n this.cache[key] = new Program(\n this.context,\n shaders[name],\n programConfiguration,\n programUniforms[name],\n this._showOverdrawInspector,\n this.style.map.terrain\n );\n }\n return this.cache[key];\n }\n\n /*\n * Reset some GL state to default values to avoid hard-to-debug bugs\n * in custom layers.\n */\n setCustomLayerDefaults() {\n // Prevent custom layers from unintentionally modify the last VAO used.\n // All other state is state is restored on it's own, but for VAOs it's\n // simpler to unbind so that we don't have to track the state of VAOs.\n this.context.unbindVAO();\n\n // The default values for this state is meaningful and often expected.\n // Leaving this state dirty could cause a lot of confusion for users.\n this.context.cullFace.setDefault();\n this.context.activeTexture.setDefault();\n this.context.pixelStoreUnpack.setDefault();\n this.context.pixelStoreUnpackPremultiplyAlpha.setDefault();\n this.context.pixelStoreUnpackFlipY.setDefault();\n }\n\n /*\n * Set GL state that is shared by all layers.\n */\n setBaseState() {\n const gl = this.context.gl;\n this.context.cullFace.set(false);\n this.context.viewport.set([0, 0, this.width, this.height]);\n this.context.blendEquation.set(gl.FUNC_ADD);\n }\n\n initDebugOverlayCanvas() {\n if (this.debugOverlayCanvas == null) {\n this.debugOverlayCanvas = document.createElement('canvas');\n this.debugOverlayCanvas.width = 512;\n this.debugOverlayCanvas.height = 512;\n const gl = this.context.gl;\n this.debugOverlayTexture = new Texture(this.context, this.debugOverlayCanvas, gl.RGBA);\n }\n }\n\n destroy() {\n if (this.debugOverlayTexture) {\n this.debugOverlayTexture.destroy();\n }\n }\n\n /*\n * Return true if drawing buffer size is != from requested size.\n * That means that we've reached GL limits somehow.\n * Note: drawing buffer size changes only when canvas size changes\n */\n overLimit() {\n const {drawingBufferWidth, drawingBufferHeight} = this.context.gl;\n return this.width !== drawingBufferWidth || this.height !== drawingBufferHeight;\n }\n}\n","import {StencilMode} from '../gl/stencil_mode';\nimport {DepthMode} from '../gl/depth_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {PosArray, TriangleIndexArray} from '../data/array_types.g';\nimport posAttributes from '../data/pos_attributes';\nimport {SegmentVector} from '../data/segment';\nimport {skyUniformValues} from './program/sky_program';\nimport {Sky} from '../style/sky';\nimport {Mesh} from './mesh';\nimport type {Painter} from './painter';\n\nexport function drawSky(painter: Painter, sky: Sky) {\n const context = painter.context;\n const gl = context.gl;\n\n const skyUniforms = skyUniformValues(sky, painter.style.map.transform, painter.pixelRatio);\n\n const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);\n const stencilMode = StencilMode.disabled;\n const colorMode = painter.colorModeForRenderPass();\n const program = painter.useProgram('sky');\n\n if (!sky.mesh) {\n const vertexArray = new PosArray();\n vertexArray.emplaceBack(-1, -1);\n vertexArray.emplaceBack(1, -1);\n vertexArray.emplaceBack(1, 1);\n vertexArray.emplaceBack(-1, 1);\n\n const indexArray = new TriangleIndexArray();\n indexArray.emplaceBack(0, 1, 2);\n indexArray.emplaceBack(0, 2, 3);\n\n sky.mesh = new Mesh(\n context.createVertexBuffer(vertexArray, posAttributes.members),\n context.createIndexBuffer(indexArray),\n SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length)\n );\n }\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode,\n CullFaceMode.disabled, skyUniforms, undefined, 'sky', sky.mesh.vertexBuffer,\n sky.mesh.indexBuffer, sky.mesh.segments);\n}\n","import {StencilMode} from '../gl/stencil_mode';\nimport {DepthMode} from '../gl/depth_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {Program} from './program';\nimport {circleUniformValues} from './program/circle_program';\nimport {SegmentVector} from '../data/segment';\nimport {OverscaledTileID} from '../source/tile_id';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {CircleStyleLayer} from '../style/style_layer/circle_style_layer';\nimport type {CircleBucket} from '../data/bucket/circle_bucket';\nimport type {ProgramConfiguration} from '../data/program_configuration';\nimport type {VertexBuffer} from '../gl/vertex_buffer';\nimport type {IndexBuffer} from '../gl/index_buffer';\nimport type {UniformValues} from './uniform_binding';\nimport type {CircleUniformsType} from './program/circle_program';\nimport type {TerrainData} from '../render/terrain';\n\ntype TileRenderState = {\n programConfiguration: ProgramConfiguration;\n program: Program;\n layoutVertexBuffer: VertexBuffer;\n indexBuffer: IndexBuffer;\n uniformValues: UniformValues;\n terrainData: TerrainData;\n};\n\ntype SegmentsTileRenderState = {\n segments: SegmentVector;\n sortKey: number;\n state: TileRenderState;\n};\n\nexport function drawCircles(painter: Painter, sourceCache: SourceCache, layer: CircleStyleLayer, coords: Array) {\n if (painter.renderPass !== 'translucent') return;\n\n const opacity = layer.paint.get('circle-opacity');\n const strokeWidth = layer.paint.get('circle-stroke-width');\n const strokeOpacity = layer.paint.get('circle-stroke-opacity');\n const sortFeaturesByKey = !layer.layout.get('circle-sort-key').isConstant();\n\n if (opacity.constantOr(1) === 0 && (strokeWidth.constantOr(1) === 0 || strokeOpacity.constantOr(1) === 0)) {\n return;\n }\n\n const context = painter.context;\n const gl = context.gl;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n // Turn off stencil testing to allow circles to be drawn across boundaries,\n // so that large circles are not clipped to tiles\n const stencilMode = StencilMode.disabled;\n const colorMode = painter.colorModeForRenderPass();\n\n const segmentsRenderStates: Array = [];\n\n for (let i = 0; i < coords.length; i++) {\n const coord = coords[i];\n\n const tile = sourceCache.getTile(coord);\n const bucket: CircleBucket = (tile.getBucket(layer) as any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram('circle', programConfiguration);\n const layoutVertexBuffer = bucket.layoutVertexBuffer;\n const indexBuffer = bucket.indexBuffer;\n const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord);\n const uniformValues = circleUniformValues(painter, coord, tile, layer);\n\n const state: TileRenderState = {\n programConfiguration,\n program,\n layoutVertexBuffer,\n indexBuffer,\n uniformValues,\n terrainData\n };\n\n if (sortFeaturesByKey) {\n const oldSegments = bucket.segments.get();\n for (const segment of oldSegments) {\n segmentsRenderStates.push({\n segments: new SegmentVector([segment]),\n sortKey: (segment.sortKey as any as number),\n state\n });\n }\n } else {\n segmentsRenderStates.push({\n segments: bucket.segments,\n sortKey: 0,\n state\n });\n }\n\n }\n\n if (sortFeaturesByKey) {\n segmentsRenderStates.sort((a, b) => a.sortKey - b.sortKey);\n }\n\n for (const segmentsState of segmentsRenderStates) {\n const {programConfiguration, program, layoutVertexBuffer, indexBuffer, uniformValues, terrainData} = segmentsState.state;\n const segments = segmentsState.segments;\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, terrainData, layer.id,\n layoutVertexBuffer, indexBuffer, segments,\n layer.paint, painter.transform.zoom, programConfiguration);\n }\n}\n","import {DepthMode} from '../gl/depth_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {Texture} from './texture';\nimport {\n lineUniformValues,\n linePatternUniformValues,\n lineSDFUniformValues,\n lineGradientUniformValues\n} from './program/line_program';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {LineStyleLayer} from '../style/style_layer/line_style_layer';\nimport type {LineBucket} from '../data/bucket/line_bucket';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport {clamp, nextPowerOfTwo} from '../util/util';\nimport {renderColorRamp} from '../util/color_ramp';\nimport {EXTENT} from '../data/extent';\n\nexport function drawLine(painter: Painter, sourceCache: SourceCache, layer: LineStyleLayer, coords: Array) {\n if (painter.renderPass !== 'translucent') return;\n\n const opacity = layer.paint.get('line-opacity');\n const width = layer.paint.get('line-width');\n if (opacity.constantOr(1) === 0 || width.constantOr(1) === 0) return;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n const colorMode = painter.colorModeForRenderPass();\n\n const dasharray = layer.paint.get('line-dasharray');\n const patternProperty = layer.paint.get('line-pattern');\n const image = patternProperty.constantOr(1 as any);\n\n const gradient = layer.paint.get('line-gradient');\n const crossfade = layer.getCrossfadeParameters();\n\n const programId =\n image ? 'linePattern' :\n dasharray ? 'lineSDF' :\n gradient ? 'lineGradient' : 'line';\n\n const context = painter.context;\n const gl = context.gl;\n\n let firstTile = true;\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n\n if (image && !tile.patternsLoaded()) continue;\n\n const bucket: LineBucket = (tile.getBucket(layer) as any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const prevProgram = painter.context.program.get();\n const program = painter.useProgram(programId, programConfiguration);\n const programChanged = firstTile || program.program !== prevProgram;\n const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord);\n\n const constantPattern = patternProperty.constantOr(null);\n if (constantPattern && tile.imageAtlas) {\n const atlas = tile.imageAtlas;\n const posTo = atlas.patternPositions[constantPattern.to.toString()];\n const posFrom = atlas.patternPositions[constantPattern.from.toString()];\n if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);\n }\n\n const terrainCoord = terrainData ? coord : null;\n const uniformValues = image ? linePatternUniformValues(painter, tile, layer, crossfade, terrainCoord) :\n dasharray ? lineSDFUniformValues(painter, tile, layer, dasharray, crossfade, terrainCoord) :\n gradient ? lineGradientUniformValues(painter, tile, layer, bucket.lineClipsArray.length, terrainCoord) :\n lineUniformValues(painter, tile, layer, terrainCoord);\n\n if (image) {\n context.activeTexture.set(gl.TEXTURE0);\n tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n programConfiguration.updatePaintBuffers(crossfade);\n } else if (dasharray && (programChanged || painter.lineAtlas.dirty)) {\n context.activeTexture.set(gl.TEXTURE0);\n painter.lineAtlas.bind(context);\n } else if (gradient) {\n const layerGradient = bucket.gradients[layer.id];\n let gradientTexture = layerGradient.texture;\n if (layer.gradientVersion !== layerGradient.version) {\n let textureResolution = 256;\n if (layer.stepInterpolant) {\n const sourceMaxZoom = sourceCache.getSource().maxzoom;\n const potentialOverzoom = coord.canonical.z === sourceMaxZoom ?\n Math.ceil(1 << (painter.transform.maxZoom - coord.canonical.z)) : 1;\n const lineLength = bucket.maxLineLength / EXTENT;\n // Logical pixel tile size is 512px, and 1024px right before current zoom + 1\n const maxTilePixelSize = 1024;\n // Maximum possible texture coverage heuristic, bound by hardware max texture size\n const maxTextureCoverage = lineLength * maxTilePixelSize * potentialOverzoom;\n textureResolution = clamp(nextPowerOfTwo(maxTextureCoverage), 256, context.maxTextureSize);\n }\n layerGradient.gradient = renderColorRamp({\n expression: layer.gradientExpression(),\n evaluationKey: 'lineProgress',\n resolution: textureResolution,\n image: layerGradient.gradient || undefined,\n clips: bucket.lineClipsArray\n });\n if (layerGradient.texture) {\n layerGradient.texture.update(layerGradient.gradient);\n } else {\n layerGradient.texture = new Texture(context, layerGradient.gradient, gl.RGBA);\n }\n layerGradient.version = layer.gradientVersion;\n gradientTexture = layerGradient.texture;\n }\n context.activeTexture.set(gl.TEXTURE0);\n gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE);\n }\n\n program.draw(context, gl.TRIANGLES, depthMode,\n painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, terrainData,\n layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments,\n layer.paint, painter.transform.zoom, programConfiguration, bucket.layoutVertexBuffer2);\n\n firstTile = false;\n // once refactored so that bound texture state is managed, we'll also be able to remove this firstTile/programChanged logic\n }\n}\n","import {StencilMode} from '../gl/stencil_mode';\nimport {DepthMode} from '../gl/depth_mode';\nimport {CullFaceMode} from '../gl/cull_face_mode';\nimport {\n backgroundUniformValues,\n backgroundPatternUniformValues\n} from './program/background_program';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {BackgroundStyleLayer} from '../style/style_layer/background_style_layer';\nimport {OverscaledTileID} from '../source/tile_id';\n\nexport function drawBackground(painter: Painter, sourceCache: SourceCache, layer: BackgroundStyleLayer, coords?: Array) {\n const color = layer.paint.get('background-color');\n const opacity = layer.paint.get('background-opacity');\n\n if (opacity === 0) return;\n\n const context = painter.context;\n const gl = context.gl;\n const transform = painter.transform;\n const tileSize = transform.tileSize;\n const image = layer.paint.get('background-pattern');\n if (painter.isPatternMissing(image)) return;\n\n const pass = (!image && color.a === 1 && opacity === 1 && painter.opaquePassEnabledForLayer()) ? 'opaque' : 'translucent';\n if (painter.renderPass !== pass) return;\n\n const stencilMode = StencilMode.disabled;\n const depthMode = painter.depthModeForSublayer(0, pass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);\n const colorMode = painter.colorModeForRenderPass();\n const program = painter.useProgram(image ? 'backgroundPattern' : 'background');\n const tileIDs = coords ? coords : transform.coveringTiles({tileSize, terrain: painter.style.map.terrain});\n\n if (image) {\n context.activeTexture.set(gl.TEXTURE0);\n painter.imageManager.bind(painter.context);\n }\n\n const crossfade = layer.getCrossfadeParameters();\n for (const tileID of tileIDs) {\n const matrix = coords ? tileID.posMatrix : painter.transform.calculatePosMatrix(tileID.toUnwrapped());\n const uniformValues = image ?\n backgroundPatternUniformValues(matrix, opacity, painter, image, {tileID, tileSize}, crossfade) :\n backgroundUniformValues(matrix, opacity, color);\n const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(tileID);\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, terrainData, layer.id, painter.tileExtentBuffer,\n painter.quadTriangleIndexBuffer, painter.tileExtentSegments);\n }\n}\n","import {DepthMode} from '../gl/depth_mode';\nimport {StencilMode} from '../gl/stencil_mode';\n\nimport type {Painter} from './painter';\nimport type {SourceCache} from '../source/source_cache';\nimport type {CustomStyleLayer} from '../style/style_layer/custom_style_layer';\n\nexport function drawCustom(painter: Painter, sourceCache: SourceCache, layer: CustomStyleLayer) {\n\n const context = painter.context;\n const implementation = layer.implementation;\n\n if (painter.renderPass === 'offscreen') {\n\n const prerender = implementation.prerender;\n if (prerender) {\n painter.setCustomLayerDefaults();\n context.setColorMode(painter.colorModeForRenderPass());\n\n prerender.call(implementation, context.gl, painter.transform.customLayerMatrix());\n\n context.setDirty();\n painter.setBaseState();\n }\n\n } else if (painter.renderPass === 'translucent') {\n\n painter.setCustomLayerDefaults();\n\n context.setColorMode(painter.colorModeForRenderPass());\n context.setStencilMode(StencilMode.disabled);\n\n const depthMode = implementation.renderingMode === '3d' ?\n new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D) :\n painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n\n context.setDepthMode(depthMode);\n\n implementation.render(context.gl, painter.transform.customLayerMatrix(), {farZ: painter.transform.farZ, nearZ: painter.transform.nearZ, fov: painter.transform._fov, modelViewProjectionMatrix: painter.transform.modelViewProjectionMatrix, projectionMatrix: painter.transform.projectionMatrix});\n\n context.setDirty();\n painter.setBaseState();\n context.bindFramebuffer.set(null);\n }\n}\n","import {mat4, vec3, vec4} from 'gl-matrix';\n\nclass Frustum {\n\n constructor(public points: vec4[], public planes: vec4[]) { }\n\n public static fromInvProjectionMatrix(invProj: mat4, worldSize: number, zoom: number): Frustum {\n const clipSpaceCorners = [\n [-1, 1, -1, 1],\n [1, 1, -1, 1],\n [1, -1, -1, 1],\n [-1, -1, -1, 1],\n [-1, 1, 1, 1],\n [1, 1, 1, 1],\n [1, -1, 1, 1],\n [-1, -1, 1, 1]\n ];\n\n const scale = Math.pow(2, zoom);\n\n // Transform frustum corner points from clip space to tile space, Z to meters\n const frustumCoords = clipSpaceCorners.map(v => {\n v = vec4.transformMat4([] as any, v as any, invProj) as any;\n const s = 1.0 / v[3] / worldSize * scale;\n return vec4.mul(v as any, v as any, [s, s, 1.0 / v[3], s] as vec4);\n });\n\n const frustumPlanePointIndices = [\n [0, 1, 2], // near\n [6, 5, 4], // far\n [0, 3, 7], // left\n [2, 1, 5], // right\n [3, 2, 6], // bottom\n [0, 4, 5] // top\n ];\n\n const frustumPlanes = frustumPlanePointIndices.map((p: number[]) => {\n const a = vec3.sub([] as any, frustumCoords[p[0]] as vec3, frustumCoords[p[1]] as vec3);\n const b = vec3.sub([] as any, frustumCoords[p[2]] as vec3, frustumCoords[p[1]] as vec3);\n const n = vec3.normalize([] as any, vec3.cross([] as any, a, b)) as any;\n const d = -vec3.dot(n, frustumCoords[p[1]] as vec3);\n return n.concat(d);\n });\n\n return new Frustum(frustumCoords, frustumPlanes);\n }\n}\n\nclass Aabb {\n min: vec3;\n max: vec3;\n center: vec3;\n\n constructor(min_: vec3, max_: vec3) {\n this.min = min_;\n this.max = max_;\n this.center = vec3.scale([] as any, vec3.add([] as any, this.min, this.max), 0.5);\n }\n\n quadrant(index: number): Aabb {\n const split = [(index % 2) === 0, index < 2];\n const qMin = vec3.clone(this.min);\n const qMax = vec3.clone(this.max);\n for (let axis = 0; axis < split.length; axis++) {\n qMin[axis] = split[axis] ? this.min[axis] : this.center[axis];\n qMax[axis] = split[axis] ? this.center[axis] : this.max[axis];\n }\n // Elevation is always constant, hence quadrant.max.z = this.max.z\n qMax[2] = this.max[2];\n return new Aabb(qMin, qMax);\n }\n\n distanceX(point: Array): number {\n const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]);\n return pointOnAabb - point[0];\n }\n\n distanceY(point: Array): number {\n const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]);\n return pointOnAabb - point[1];\n }\n\n // Performs a frustum-aabb intersection test. Returns 0 if there's no intersection,\n // 1 if shapes are intersecting and 2 if the aabb if fully inside the frustum.\n intersects(frustum: Frustum): number {\n // Execute separating axis test between two convex objects to find intersections\n // Each frustum plane together with 3 major axes define the separating axes\n\n const aabbPoints = [\n [this.min[0], this.min[1], this.min[2], 1],\n [this.max[0], this.min[1], this.min[2], 1],\n [this.max[0], this.max[1], this.min[2], 1],\n [this.min[0], this.max[1], this.min[2], 1],\n [this.min[0], this.min[1], this.max[2], 1],\n [this.max[0], this.min[1], this.max[2], 1],\n [this.max[0], this.max[1], this.max[2], 1],\n [this.min[0], this.max[1], this.max[2], 1]\n ];\n\n let fullyInside = true;\n\n for (let p = 0; p < frustum.planes.length; p++) {\n const plane = frustum.planes[p];\n let pointsInside = 0;\n\n for (let i = 0; i < aabbPoints.length; i++) {\n if (vec4.dot(plane, aabbPoints[i] as any) >= 0) {\n pointsInside++;\n }\n }\n\n if (pointsInside === 0)\n return 0;\n\n if (pointsInside !== aabbPoints.length)\n fullyInside = false;\n }\n\n if (fullyInside)\n return 2;\n\n for (let axis = 0; axis < 3; axis++) {\n let projMin = Number.MAX_VALUE;\n let projMax = -Number.MAX_VALUE;\n\n for (let p = 0; p < frustum.points.length; p++) {\n const projectedPoint = frustum.points[p][axis] - this.min[axis];\n\n projMin = Math.min(projMin, projectedPoint);\n projMax = Math.max(projMax, projectedPoint);\n }\n\n if (projMax < 0 || projMin > this.max[axis] - this.min[axis])\n return 0;\n }\n\n return 1;\n }\n}\nexport {\n Aabb,\n Frustum\n};\n","import {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport Point from '@mapbox/point-geometry';\nimport {clamp} from '../util/util';\n\n/**\n * An `EdgeInset` object represents screen space padding applied to the edges of the viewport.\n * This shifts the apprent center or the vanishing point of the map. This is useful for adding floating UI elements\n * on top of the map and having the vanishing point shift as UI elements resize.\n *\n * @group Geography and Geometry\n */\nexport class EdgeInsets {\n /**\n * @defaultValue 0\n */\n top: number;\n /**\n * @defaultValue 0\n */\n bottom: number;\n /**\n * @defaultValue 0\n */\n left: number;\n /**\n * @defaultValue 0\n */\n right: number;\n\n constructor(top: number = 0, bottom: number = 0, left: number = 0, right: number = 0) {\n if (isNaN(top) || top < 0 ||\n isNaN(bottom) || bottom < 0 ||\n isNaN(left) || left < 0 ||\n isNaN(right) || right < 0\n ) {\n throw new Error('Invalid value for edge-insets, top, bottom, left and right must all be numbers');\n }\n\n this.top = top;\n this.bottom = bottom;\n this.left = left;\n this.right = right;\n }\n\n /**\n * Interpolates the inset in-place.\n * This maintains the current inset value for any inset not present in `target`.\n * @param start - interpolation start\n * @param target - interpolation target\n * @param t - interpolation step/weight\n * @returns the insets\n */\n interpolate(start: PaddingOptions | EdgeInsets, target: PaddingOptions, t: number): EdgeInsets {\n if (target.top != null && start.top != null) this.top = interpolates.number(start.top, target.top, t);\n if (target.bottom != null && start.bottom != null) this.bottom = interpolates.number(start.bottom, target.bottom, t);\n if (target.left != null && start.left != null) this.left = interpolates.number(start.left, target.left, t);\n if (target.right != null && start.right != null) this.right = interpolates.number(start.right, target.right, t);\n\n return this;\n }\n\n /**\n * Utility method that computes the new apprent center or vanishing point after applying insets.\n * This is in pixels and with the top left being (0.0) and +y being downwards.\n *\n * @param width - the width\n * @param height - the height\n * @returns the point\n */\n getCenter(width: number, height: number): Point {\n // Clamp insets so they never overflow width/height and always calculate a valid center\n const x = clamp((this.left + width - this.right) / 2, 0, width);\n const y = clamp((this.top + height - this.bottom) / 2, 0, height);\n\n return new Point(x, y);\n }\n\n equals(other: PaddingOptions): boolean {\n return this.top === other.top &&\n this.bottom === other.bottom &&\n this.left === other.left &&\n this.right === other.right;\n }\n\n clone(): EdgeInsets {\n return new EdgeInsets(this.top, this.bottom, this.left, this.right);\n }\n\n /**\n * Returns the current state as json, useful when you want to have a\n * read-only representation of the inset.\n *\n * @returns state as json\n */\n toJSON(): PaddingOptions {\n return {\n top: this.top,\n bottom: this.bottom,\n left: this.left,\n right: this.right\n };\n }\n}\n\n/**\n * Options for setting padding on calls to methods such as {@link Map#fitBounds}, {@link Map#fitScreenCoordinates}, and {@link Map#setPadding}. Adjust these options to set the amount of padding in pixels added to the edges of the canvas. Set a uniform padding on all edges or individual values for each edge. All properties of this object must be\n * non-negative integers.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let bbox = [[-79, 43], [-73, 45]];\n * map.fitBounds(bbox, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * ```\n *\n * @example\n * ```ts\n * let bbox = [[-79, 43], [-73, 45]];\n * map.fitBounds(bbox, {\n * padding: 20\n * });\n * ```\n * @see [Fit to the bounds of a LineString](https://maplibre.org/maplibre-gl-js/docs/examples/zoomto-linestring/)\n * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fitbounds/)\n */\nexport type PaddingOptions = {\n /**\n * Padding in pixels from the top of the map canvas.\n */\n top: number;\n /**\n * Padding in pixels from the bottom of the map canvas.\n */\n bottom: number;\n /**\n * Padding in pixels from the left of the map canvas.\n */\n right: number;\n /**\n * Padding in pixels from the right of the map canvas.\n */\n left: number;\n};\n","import {LngLat} from './lng_lat';\nimport {LngLatBounds} from './lng_lat_bounds';\nimport {MercatorCoordinate, mercatorXfromLng, mercatorYfromLat, mercatorZfromAltitude} from './mercator_coordinate';\nimport Point from '@mapbox/point-geometry';\nimport {wrap, clamp} from '../util/util';\nimport {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {EXTENT} from '../data/extent';\nimport {vec3, vec4, mat4, mat2, vec2} from 'gl-matrix';\nimport {Aabb, Frustum} from '../util/primitives';\nimport {EdgeInsets} from './edge_insets';\n\nimport {UnwrappedTileID, OverscaledTileID, CanonicalTileID} from '../source/tile_id';\nimport type {PaddingOptions} from './edge_insets';\nimport {Terrain} from '../render/terrain';\n\nexport const MAX_VALID_LATITUDE = 85.051129;\n\n/**\n * @internal\n * A single transform, generally used for a single tile to be\n * scaled, rotated, and zoomed.\n */\nexport class Transform {\n tileSize: number;\n tileZoom: number;\n lngRange: [number, number];\n latRange: [number, number];\n scale: number;\n width: number;\n height: number;\n angle: number;\n rotationMatrix: mat2;\n pixelsToGLUnits: [number, number];\n cameraToCenterDistance: number;\n mercatorMatrix: mat4;\n projectionMatrix: mat4;\n modelViewProjectionMatrix: mat4;\n invModelViewProjectionMatrix: mat4;\n alignedModelViewProjectionMatrix: mat4;\n fogMatrix: mat4;\n pixelMatrix: mat4;\n pixelMatrix3D: mat4;\n pixelMatrixInverse: mat4;\n glCoordMatrix: mat4;\n labelPlaneMatrix: mat4;\n minElevationForCurrentTile: number;\n _fov: number;\n _pitch: number;\n _zoom: number;\n _unmodified: boolean;\n _renderWorldCopies: boolean;\n _minZoom: number;\n _maxZoom: number;\n _minPitch: number;\n _maxPitch: number;\n _center: LngLat;\n _elevation: number;\n _pixelPerMeter: number;\n _edgeInsets: EdgeInsets;\n _constraining: boolean;\n _posMatrixCache: {[_: string]: mat4};\n _alignedPosMatrixCache: {[_: string]: mat4};\n _fogMatrixCache: {[_: string]: mat4};\n /**\n * This value represents the distance from the camera to the far clipping plane.\n * It is used in the calculation of the projection matrix to determine which objects are visible.\n * farZ should be larger than nearZ.\n */\n farZ: number;\n /**\n * This value represents the distance from the camera to the near clipping plane.\n * It is used in the calculation of the projection matrix to determine which objects are visible.\n * nearZ should be smaller than farZ.\n */\n nearZ: number;\n\n constructor(minZoom?: number, maxZoom?: number, minPitch?: number, maxPitch?: number, renderWorldCopies?: boolean) {\n this.tileSize = 512; // constant\n\n this._renderWorldCopies = renderWorldCopies === undefined ? true : !!renderWorldCopies;\n this._minZoom = minZoom || 0;\n this._maxZoom = maxZoom || 22;\n\n this._minPitch = (minPitch === undefined || minPitch === null) ? 0 : minPitch;\n this._maxPitch = (maxPitch === undefined || maxPitch === null) ? 60 : maxPitch;\n\n this.setMaxBounds();\n\n this.width = 0;\n this.height = 0;\n this._center = new LngLat(0, 0);\n this._elevation = 0;\n this.zoom = 0;\n this.angle = 0;\n this._fov = 0.6435011087932844;\n this._pitch = 0;\n this._unmodified = true;\n this._edgeInsets = new EdgeInsets();\n this._posMatrixCache = {};\n this._alignedPosMatrixCache = {};\n this._fogMatrixCache = {};\n this.minElevationForCurrentTile = 0;\n }\n\n clone(): Transform {\n const clone = new Transform(this._minZoom, this._maxZoom, this._minPitch, this.maxPitch, this._renderWorldCopies);\n clone.apply(this);\n return clone;\n }\n\n apply(that: Transform) {\n this.tileSize = that.tileSize;\n this.latRange = that.latRange;\n this.lngRange = that.lngRange;\n this.width = that.width;\n this.height = that.height;\n this._center = that._center;\n this._elevation = that._elevation;\n this.minElevationForCurrentTile = that.minElevationForCurrentTile;\n this.zoom = that.zoom;\n this.angle = that.angle;\n this._fov = that._fov;\n this._pitch = that._pitch;\n this._unmodified = that._unmodified;\n this._edgeInsets = that._edgeInsets.clone();\n this._calcMatrices();\n }\n\n get minZoom(): number { return this._minZoom; }\n set minZoom(zoom: number) {\n if (this._minZoom === zoom) return;\n this._minZoom = zoom;\n this.zoom = Math.max(this.zoom, zoom);\n }\n\n get maxZoom(): number { return this._maxZoom; }\n set maxZoom(zoom: number) {\n if (this._maxZoom === zoom) return;\n this._maxZoom = zoom;\n this.zoom = Math.min(this.zoom, zoom);\n }\n\n get minPitch(): number { return this._minPitch; }\n set minPitch(pitch: number) {\n if (this._minPitch === pitch) return;\n this._minPitch = pitch;\n this.pitch = Math.max(this.pitch, pitch);\n }\n\n get maxPitch(): number { return this._maxPitch; }\n set maxPitch(pitch: number) {\n if (this._maxPitch === pitch) return;\n this._maxPitch = pitch;\n this.pitch = Math.min(this.pitch, pitch);\n }\n\n get renderWorldCopies(): boolean { return this._renderWorldCopies; }\n set renderWorldCopies(renderWorldCopies: boolean) {\n if (renderWorldCopies === undefined) {\n renderWorldCopies = true;\n } else if (renderWorldCopies === null) {\n renderWorldCopies = false;\n }\n\n this._renderWorldCopies = renderWorldCopies;\n }\n\n get worldSize(): number {\n return this.tileSize * this.scale;\n }\n\n get centerOffset(): Point {\n return this.centerPoint._sub(this.size._div(2));\n }\n\n get size(): Point {\n return new Point(this.width, this.height);\n }\n\n get bearing(): number {\n return -this.angle / Math.PI * 180;\n }\n set bearing(bearing: number) {\n const b = -wrap(bearing, -180, 180) * Math.PI / 180;\n if (this.angle === b) return;\n this._unmodified = false;\n this.angle = b;\n this._calcMatrices();\n\n // 2x2 matrix for rotating points\n this.rotationMatrix = mat2.create();\n mat2.rotate(this.rotationMatrix, this.rotationMatrix, this.angle);\n }\n\n get pitch(): number {\n return this._pitch / Math.PI * 180;\n }\n set pitch(pitch: number) {\n const p = clamp(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI;\n if (this._pitch === p) return;\n this._unmodified = false;\n this._pitch = p;\n this._calcMatrices();\n }\n\n get fov(): number {\n return this._fov / Math.PI * 180;\n }\n set fov(fov: number) {\n fov = Math.max(0.01, Math.min(60, fov));\n if (this._fov === fov) return;\n this._unmodified = false;\n this._fov = fov / 180 * Math.PI;\n this._calcMatrices();\n }\n\n get zoom(): number { return this._zoom; }\n set zoom(zoom: number) {\n const constrainedZoom = Math.min(Math.max(zoom, this.minZoom), this.maxZoom);\n if (this._zoom === constrainedZoom) return;\n this._unmodified = false;\n this._zoom = constrainedZoom;\n this.tileZoom = Math.max(0, Math.floor(constrainedZoom));\n this.scale = this.zoomScale(constrainedZoom);\n this._constrain();\n this._calcMatrices();\n }\n\n get center(): LngLat { return this._center; }\n set center(center: LngLat) {\n if (center.lat === this._center.lat && center.lng === this._center.lng) return;\n this._unmodified = false;\n this._center = center;\n this._constrain();\n this._calcMatrices();\n }\n\n /**\n * Elevation at current center point, meters above sea level\n */\n get elevation(): number { return this._elevation; }\n set elevation(elevation: number) {\n if (elevation === this._elevation) return;\n this._elevation = elevation;\n this._constrain();\n this._calcMatrices();\n }\n\n get padding(): PaddingOptions { return this._edgeInsets.toJSON(); }\n set padding(padding: PaddingOptions) {\n if (this._edgeInsets.equals(padding)) return;\n this._unmodified = false;\n //Update edge-insets in place\n this._edgeInsets.interpolate(this._edgeInsets, padding, 1);\n this._calcMatrices();\n }\n\n /**\n * The center of the screen in pixels with the top-left corner being (0,0)\n * and +y axis pointing downwards. This accounts for padding.\n */\n get centerPoint(): Point {\n return this._edgeInsets.getCenter(this.width, this.height);\n }\n\n /**\n * Returns if the padding params match\n *\n * @param padding - the padding to check against\n * @returns true if they are equal, false otherwise\n */\n isPaddingEqual(padding: PaddingOptions): boolean {\n return this._edgeInsets.equals(padding);\n }\n\n /**\n * Helper method to update edge-insets in place\n *\n * @param start - the starting padding\n * @param target - the target padding\n * @param t - the step/weight\n */\n interpolatePadding(start: PaddingOptions, target: PaddingOptions, t: number) {\n this._unmodified = false;\n this._edgeInsets.interpolate(start, target, t);\n this._constrain();\n this._calcMatrices();\n }\n\n /**\n * Return a zoom level that will cover all tiles the transform\n * @param options - the options\n * @returns zoom level An integer zoom level at which all tiles will be visible.\n */\n coveringZoomLevel(options: {\n /**\n * Target zoom level. If true, the value will be rounded to the closest integer. Otherwise the value will be floored.\n */\n roundZoom?: boolean;\n /**\n * Tile size, expressed in screen pixels.\n */\n tileSize: number;\n }): number {\n const z = (options.roundZoom ? Math.round : Math.floor)(\n this.zoom + this.scaleZoom(this.tileSize / options.tileSize)\n );\n // At negative zoom levels load tiles from z0 because negative tile zoom levels don't exist.\n return Math.max(0, z);\n }\n\n /**\n * Return any \"wrapped\" copies of a given tile coordinate that are visible\n * in the current view.\n */\n getVisibleUnwrappedCoordinates(tileID: CanonicalTileID) {\n const result = [new UnwrappedTileID(0, tileID)];\n if (this._renderWorldCopies) {\n const utl = this.pointCoordinate(new Point(0, 0));\n const utr = this.pointCoordinate(new Point(this.width, 0));\n const ubl = this.pointCoordinate(new Point(this.width, this.height));\n const ubr = this.pointCoordinate(new Point(0, this.height));\n const w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x));\n const w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x));\n\n // Add an extra copy of the world on each side to properly render ImageSources and CanvasSources.\n // Both sources draw outside the tile boundaries of the tile that \"contains them\" so we need\n // to add extra copies on both sides in case offscreen tiles need to draw into on-screen ones.\n const extraWorldCopy = 1;\n\n for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) {\n if (w === 0) continue;\n result.push(new UnwrappedTileID(w, tileID));\n }\n }\n return result;\n }\n\n /**\n * Return all coordinates that could cover this transform for a covering\n * zoom level.\n * @param options - the options\n * @returns OverscaledTileIDs\n */\n coveringTiles(\n options: {\n tileSize: number;\n minzoom?: number;\n maxzoom?: number;\n roundZoom?: boolean;\n reparseOverscaled?: boolean;\n renderWorldCopies?: boolean;\n terrain?: Terrain;\n }\n ): Array {\n let z = this.coveringZoomLevel(options);\n const actualZ = z;\n\n if (options.minzoom !== undefined && z < options.minzoom) return [];\n if (options.maxzoom !== undefined && z > options.maxzoom) z = options.maxzoom;\n\n const cameraCoord = this.pointCoordinate(this.getCameraPoint());\n const centerCoord = MercatorCoordinate.fromLngLat(this.center);\n const numTiles = Math.pow(2, z);\n const cameraPoint = [numTiles * cameraCoord.x, numTiles * cameraCoord.y, 0];\n const centerPoint = [numTiles * centerCoord.x, numTiles * centerCoord.y, 0];\n const cameraFrustum = Frustum.fromInvProjectionMatrix(this.invModelViewProjectionMatrix, this.worldSize, z);\n\n // No change of LOD behavior for pitch lower than 60 and when there is no top padding: return only tile ids from the requested zoom level\n let minZoom = options.minzoom || 0;\n // Use 0.1 as an epsilon to avoid for explicit == 0.0 floating point checks\n if (!options.terrain && this.pitch <= 60.0 && this._edgeInsets.top < 0.1)\n minZoom = z;\n\n // There should always be a certain number of maximum zoom level tiles surrounding the center location in 2D or in front of the camera in 3D\n const radiusOfMaxLvlLodInTiles = options.terrain ? 2 / Math.min(this.tileSize, options.tileSize) * this.tileSize : 3;\n\n const newRootTile = (wrap: number): any => {\n return {\n aabb: new Aabb([wrap * numTiles, 0, 0], [(wrap + 1) * numTiles, numTiles, 0]),\n zoom: 0,\n x: 0,\n y: 0,\n wrap,\n fullyVisible: false\n };\n };\n\n // Do a depth-first traversal to find visible tiles and proper levels of detail\n const stack = [];\n const result = [];\n const maxZoom = z;\n const overscaledZ = options.reparseOverscaled ? actualZ : z;\n\n if (this._renderWorldCopies) {\n // Render copy of the globe thrice on both sides\n for (let i = 1; i <= 3; i++) {\n stack.push(newRootTile(-i));\n stack.push(newRootTile(i));\n }\n }\n\n stack.push(newRootTile(0));\n\n while (stack.length > 0) {\n const it = stack.pop();\n const x = it.x;\n const y = it.y;\n let fullyVisible = it.fullyVisible;\n\n // Visibility of a tile is not required if any of its ancestor if fully inside the frustum\n if (!fullyVisible) {\n const intersectResult = it.aabb.intersects(cameraFrustum);\n\n if (intersectResult === 0)\n continue;\n\n fullyVisible = intersectResult === 2;\n }\n\n const refPoint = options.terrain ? cameraPoint : centerPoint;\n const distanceX = it.aabb.distanceX(refPoint);\n const distanceY = it.aabb.distanceY(refPoint);\n const longestDim = Math.max(Math.abs(distanceX), Math.abs(distanceY));\n\n // We're using distance based heuristics to determine if a tile should be split into quadrants or not.\n // radiusOfMaxLvlLodInTiles defines that there's always a certain number of maxLevel tiles next to the map center.\n // Using the fact that a parent node in quadtree is twice the size of its children (per dimension)\n // we can define distance thresholds for each relative level:\n // f(k) = offset + 2 + 4 + 8 + 16 + ... + 2^k. This is the same as \"offset+2^(k+1)-2\"\n const distToSplit = radiusOfMaxLvlLodInTiles + (1 << (maxZoom - it.zoom)) - 2;\n\n // Have we reached the target depth or is the tile too far away to be any split further?\n if (it.zoom === maxZoom || (longestDim > distToSplit && it.zoom >= minZoom)) {\n const dz = maxZoom - it.zoom, dx = cameraPoint[0] - 0.5 - (x << dz), dy = cameraPoint[1] - 0.5 - (y << dz);\n result.push({\n tileID: new OverscaledTileID(it.zoom === maxZoom ? overscaledZ : it.zoom, it.wrap, it.zoom, x, y),\n distanceSq: vec2.sqrLen([centerPoint[0] - 0.5 - x, centerPoint[1] - 0.5 - y]),\n // this variable is currently not used, but may be important to reduce the amount of loaded tiles\n tileDistanceToCamera: Math.sqrt(dx * dx + dy * dy)\n });\n continue;\n }\n\n for (let i = 0; i < 4; i++) {\n const childX = (x << 1) + (i % 2);\n const childY = (y << 1) + (i >> 1);\n const childZ = it.zoom + 1;\n let quadrant = it.aabb.quadrant(i);\n if (options.terrain) {\n const tileID = new OverscaledTileID(childZ, it.wrap, childZ, childX, childY);\n const minMax = options.terrain.getMinMaxElevation(tileID);\n const minElevation = minMax.minElevation ?? this.elevation;\n const maxElevation = minMax.maxElevation ?? this.elevation;\n quadrant = new Aabb(\n [quadrant.min[0], quadrant.min[1], minElevation] as vec3,\n [quadrant.max[0], quadrant.max[1], maxElevation] as vec3\n );\n }\n stack.push({aabb: quadrant, zoom: childZ, x: childX, y: childY, wrap: it.wrap, fullyVisible});\n }\n }\n\n return result.sort((a, b) => a.distanceSq - b.distanceSq).map(a => a.tileID);\n }\n\n resize(width: number, height: number) {\n this.width = width;\n this.height = height;\n\n this.pixelsToGLUnits = [2 / width, -2 / height];\n this._constrain();\n this._calcMatrices();\n }\n\n get unmodified(): boolean { return this._unmodified; }\n\n zoomScale(zoom: number) { return Math.pow(2, zoom); }\n scaleZoom(scale: number) { return Math.log(scale) / Math.LN2; }\n\n /**\n * Convert from LngLat to world coordinates (Mercator coordinates scaled by 512)\n * @param lnglat - the lngLat\n * @returns Point\n */\n project(lnglat: LngLat) {\n const lat = clamp(lnglat.lat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE);\n return new Point(\n mercatorXfromLng(lnglat.lng) * this.worldSize,\n mercatorYfromLat(lat) * this.worldSize);\n }\n\n /**\n * Convert from world coordinates ([0, 512],[0, 512]) to LngLat ([-180, 180], [-90, 90])\n * @param point - world coordinate\n * @returns LngLat\n */\n unproject(point: Point): LngLat {\n return new MercatorCoordinate(point.x / this.worldSize, point.y / this.worldSize).toLngLat();\n }\n\n get point(): Point { return this.project(this.center); }\n\n /**\n * get the camera position in LngLat and altitudes in meter\n * @returns An object with lngLat & altitude.\n */\n getCameraPosition(): {\n lngLat: LngLat;\n altitude: number;\n } {\n const lngLat = this.pointLocation(this.getCameraPoint());\n const altitude = Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter;\n return {lngLat, altitude: altitude + this.elevation};\n }\n\n /**\n * This method works in combination with freezeElevation activated.\n * freezeElevation is enabled during map-panning because during this the camera should sit in constant height.\n * After panning finished, call this method to recalculate the zoomlevel for the current camera-height in current terrain.\n * @param terrain - the terrain\n */\n recalculateZoom(terrain: Terrain) {\n const origElevation = this.elevation;\n const origAltitude = Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter;\n\n // find position the camera is looking on\n const center = this.pointLocation(this.centerPoint, terrain);\n const elevation = terrain.getElevationForLngLatZoom(center, this.tileZoom);\n const deltaElevation = this.elevation - elevation;\n if (!deltaElevation) return;\n\n // The camera's altitude off the ground + the ground's elevation = a constant:\n // this means the camera stays at the same total height.\n const requiredAltitude = origAltitude + origElevation - elevation;\n // Since altitude = Math.cos(this._pitch) * this.cameraToCenterDistance / pixelPerMeter:\n const requiredPixelPerMeter = Math.cos(this._pitch) * this.cameraToCenterDistance / requiredAltitude;\n // Since pixelPerMeter = mercatorZfromAltitude(1, center.lat) * worldSize:\n const requiredWorldSize = requiredPixelPerMeter / mercatorZfromAltitude(1, center.lat);\n // Since worldSize = this.tileSize * scale:\n const requiredScale = requiredWorldSize / this.tileSize;\n const zoom = this.scaleZoom(requiredScale);\n\n // update matrices\n this._elevation = elevation;\n this._center = center;\n this.zoom = zoom;\n }\n\n setLocationAtPoint(lnglat: LngLat, point: Point) {\n const a = this.pointCoordinate(point);\n const b = this.pointCoordinate(this.centerPoint);\n const loc = this.locationCoordinate(lnglat);\n const newCenter = new MercatorCoordinate(\n loc.x - (a.x - b.x),\n loc.y - (a.y - b.y));\n this.center = this.coordinateLocation(newCenter);\n if (this._renderWorldCopies) {\n this.center = this.center.wrap();\n }\n }\n\n /**\n * Given a LngLat location, return the screen point that corresponds to it\n * @param lnglat - location\n * @param terrain - optional terrain\n * @returns screen point\n */\n locationPoint(lnglat: LngLat, terrain?: Terrain): Point {\n return terrain ?\n this.coordinatePoint(this.locationCoordinate(lnglat), terrain.getElevationForLngLatZoom(lnglat, this.tileZoom), this.pixelMatrix3D) :\n this.coordinatePoint(this.locationCoordinate(lnglat));\n }\n\n /**\n * Given a point on screen, return its lnglat\n * @param p - screen point\n * @param terrain - optional terrain\n * @returns lnglat location\n */\n pointLocation(p: Point, terrain?: Terrain): LngLat {\n return this.coordinateLocation(this.pointCoordinate(p, terrain));\n }\n\n /**\n * Given a geographical lnglat, return an unrounded\n * coordinate that represents it at low zoom level.\n * @param lnglat - the location\n * @returns The mercator coordinate\n */\n locationCoordinate(lnglat: LngLat): MercatorCoordinate {\n return MercatorCoordinate.fromLngLat(lnglat);\n }\n\n /**\n * Given a Coordinate, return its geographical position.\n * @param coord - mercator coordinates\n * @returns lng and lat\n */\n coordinateLocation(coord: MercatorCoordinate): LngLat {\n return coord && coord.toLngLat();\n }\n\n /**\n * Given a Point, return its mercator coordinate.\n * @param p - the point\n * @param terrain - optional terrain\n * @returns lnglat\n */\n pointCoordinate(p: Point, terrain?: Terrain): MercatorCoordinate {\n // get point-coordinate from terrain coordinates framebuffer\n if (terrain) {\n const coordinate = terrain.pointCoordinate(p);\n if (coordinate != null) {\n return coordinate;\n }\n }\n\n // calculate point-coordinate on flat earth\n const targetZ = 0;\n // since we don't know the correct projected z value for the point,\n // unproject two points to get a line and then find the point on that\n // line with z=0\n\n const coord0 = [p.x, p.y, 0, 1] as vec4;\n const coord1 = [p.x, p.y, 1, 1] as vec4;\n\n vec4.transformMat4(coord0, coord0, this.pixelMatrixInverse);\n vec4.transformMat4(coord1, coord1, this.pixelMatrixInverse);\n\n const w0 = coord0[3];\n const w1 = coord1[3];\n const x0 = coord0[0] / w0;\n const x1 = coord1[0] / w1;\n const y0 = coord0[1] / w0;\n const y1 = coord1[1] / w1;\n const z0 = coord0[2] / w0;\n const z1 = coord1[2] / w1;\n\n const t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0);\n\n return new MercatorCoordinate(\n interpolates.number(x0, x1, t) / this.worldSize,\n interpolates.number(y0, y1, t) / this.worldSize);\n }\n\n /**\n * Given a coordinate, return the screen point that corresponds to it\n * @param coord - the coordinates\n * @param elevation - the elevation\n * @param pixelMatrix - the pixel matrix\n * @returns screen point\n */\n coordinatePoint(coord: MercatorCoordinate, elevation: number = 0, pixelMatrix = this.pixelMatrix): Point {\n const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation, 1] as vec4;\n vec4.transformMat4(p, p, pixelMatrix);\n return new Point(p[0] / p[3], p[1] / p[3]);\n }\n\n /**\n * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not\n * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.\n * @returns Returns a {@link LngLatBounds} object describing the map's geographical bounds.\n */\n getBounds(): LngLatBounds {\n const top = Math.max(0, this.height / 2 - this.getHorizon());\n return new LngLatBounds()\n .extend(this.pointLocation(new Point(0, top)))\n .extend(this.pointLocation(new Point(this.width, top)))\n .extend(this.pointLocation(new Point(this.width, this.height)))\n .extend(this.pointLocation(new Point(0, this.height)));\n }\n\n /**\n * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.\n * @returns max bounds\n */\n getMaxBounds(): LngLatBounds | null {\n if (!this.latRange || this.latRange.length !== 2 ||\n !this.lngRange || this.lngRange.length !== 2) return null;\n\n return new LngLatBounds([this.lngRange[0], this.latRange[0]], [this.lngRange[1], this.latRange[1]]);\n }\n\n /**\n * Calculate pixel height of the visible horizon in relation to map-center (e.g. height/2),\n * multiplied by a static factor to simulate the earth-radius.\n * The calculated value is the horizontal line from the camera-height to sea-level.\n * @returns Horizon above center in pixels.\n */\n getHorizon(): number {\n return Math.tan(Math.PI / 2 - this._pitch) * this.cameraToCenterDistance * 0.85;\n }\n\n /**\n * Sets or clears the map's geographical constraints.\n * @param bounds - A {@link LngLatBounds} object describing the new geographic boundaries of the map.\n */\n setMaxBounds(bounds?: LngLatBounds | null) {\n if (bounds) {\n this.lngRange = [bounds.getWest(), bounds.getEast()];\n this.latRange = [bounds.getSouth(), bounds.getNorth()];\n this._constrain();\n } else {\n this.lngRange = null;\n this.latRange = [-MAX_VALID_LATITUDE, MAX_VALID_LATITUDE];\n }\n }\n\n calculateTileMatrix(unwrappedTileID: UnwrappedTileID): mat4 {\n const canonical = unwrappedTileID.canonical;\n const scale = this.worldSize / this.zoomScale(canonical.z);\n const unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap;\n\n const worldMatrix = mat4.identity(new Float64Array(16) as any);\n mat4.translate(worldMatrix, worldMatrix, [unwrappedX * scale, canonical.y * scale, 0]);\n mat4.scale(worldMatrix, worldMatrix, [scale / EXTENT, scale / EXTENT, 1]);\n return worldMatrix;\n }\n\n /**\n * Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map.\n * @param unwrappedTileID - the tile ID\n */\n calculatePosMatrix(unwrappedTileID: UnwrappedTileID, aligned: boolean = false): mat4 {\n const posMatrixKey = unwrappedTileID.key;\n const cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache;\n if (cache[posMatrixKey]) {\n return cache[posMatrixKey];\n }\n\n const posMatrix = this.calculateTileMatrix(unwrappedTileID);\n mat4.multiply(posMatrix, aligned ? this.alignedModelViewProjectionMatrix : this.modelViewProjectionMatrix, posMatrix);\n\n cache[posMatrixKey] = new Float32Array(posMatrix);\n return cache[posMatrixKey];\n }\n\n /**\n * Calculate the fogMatrix that, given a tile coordinate, would be used to calculate fog on the map.\n * @param unwrappedTileID - the tile ID\n * @private\n */\n calculateFogMatrix(unwrappedTileID: UnwrappedTileID): mat4 {\n const posMatrixKey = unwrappedTileID.key;\n const cache = this._fogMatrixCache;\n if (cache[posMatrixKey]) {\n return cache[posMatrixKey];\n }\n\n const fogMatrix = this.calculateTileMatrix(unwrappedTileID);\n mat4.multiply(fogMatrix, this.fogMatrix, fogMatrix);\n\n cache[posMatrixKey] = new Float32Array(fogMatrix);\n return cache[posMatrixKey];\n }\n\n customLayerMatrix(): mat4 {\n return this.mercatorMatrix.slice() as any;\n }\n\n /**\n * Get center lngLat and zoom to ensure that\n * 1) everything beyond the bounds is excluded\n * 2) a given lngLat is as near the center as possible\n * Bounds are those set by maxBounds or North & South \"Poles\" and, if only 1 globe is displayed, antimeridian.\n */\n getConstrained(lngLat: LngLat, zoom: number): {center: LngLat; zoom: number} {\n zoom = clamp(+zoom, this.minZoom, this.maxZoom);\n const result = {\n center: new LngLat(lngLat.lng, lngLat.lat),\n zoom\n };\n\n let lngRange = this.lngRange;\n\n if (!this._renderWorldCopies && lngRange === null) {\n const almost180 = 180 - 1e-10;\n lngRange = [-almost180, almost180];\n }\n\n const worldSize = this.tileSize * this.zoomScale(result.zoom); // A world size for the requested zoom level, not the current world size\n let minY = 0;\n let maxY = worldSize;\n let minX = 0;\n let maxX = worldSize;\n let scaleY = 0;\n let scaleX = 0;\n const {x: screenWidth, y: screenHeight} = this.size;\n\n if (this.latRange) {\n const latRange = this.latRange;\n minY = mercatorYfromLat(latRange[1]) * worldSize;\n maxY = mercatorYfromLat(latRange[0]) * worldSize;\n const shouldZoomIn = maxY - minY < screenHeight;\n if (shouldZoomIn) scaleY = screenHeight / (maxY - minY);\n }\n\n if (lngRange) {\n minX = wrap(\n mercatorXfromLng(lngRange[0]) * worldSize,\n 0,\n worldSize\n );\n maxX = wrap(\n mercatorXfromLng(lngRange[1]) * worldSize,\n 0,\n worldSize\n );\n\n if (maxX < minX) maxX += worldSize;\n\n const shouldZoomIn = maxX - minX < screenWidth;\n if (shouldZoomIn) scaleX = screenWidth / (maxX - minX);\n }\n\n const {x: originalX, y: originalY} = this.project.call({worldSize}, lngLat);\n let modifiedX, modifiedY;\n\n const scale = Math.max(scaleX || 0, scaleY || 0);\n\n if (scale) {\n // zoom in to exclude all beyond the given lng/lat ranges\n const newPoint = new Point(\n scaleX ? (maxX + minX) / 2 : originalX,\n scaleY ? (maxY + minY) / 2 : originalY);\n result.center = this.unproject.call({worldSize}, newPoint).wrap();\n result.zoom += this.scaleZoom(scale);\n return result;\n }\n\n if (this.latRange) {\n const h2 = screenHeight / 2;\n if (originalY - h2 < minY) modifiedY = minY + h2;\n if (originalY + h2 > maxY) modifiedY = maxY - h2;\n }\n\n if (lngRange) {\n const centerX = (minX + maxX) / 2;\n let wrappedX = originalX;\n if (this._renderWorldCopies) {\n wrappedX = wrap(originalX, centerX - worldSize / 2, centerX + worldSize / 2);\n }\n const w2 = screenWidth / 2;\n\n if (wrappedX - w2 < minX) modifiedX = minX + w2;\n if (wrappedX + w2 > maxX) modifiedX = maxX - w2;\n }\n\n // pan the map if the screen goes off the range\n if (modifiedX !== undefined || modifiedY !== undefined) {\n const newPoint = new Point(modifiedX ?? originalX, modifiedY ?? originalY);\n result.center = this.unproject.call({worldSize}, newPoint).wrap();\n }\n\n return result;\n }\n\n _constrain() {\n if (!this.center || !this.width || !this.height || this._constraining) return;\n this._constraining = true;\n const unmodified = this._unmodified;\n const {center, zoom} = this.getConstrained(this.center, this.zoom);\n this.center = center;\n this.zoom = zoom;\n this._unmodified = unmodified;\n this._constraining = false;\n }\n\n _calcMatrices() {\n if (!this.height) return;\n\n const halfFov = this._fov / 2;\n const offset = this.centerOffset;\n const x = this.point.x, y = this.point.y;\n this.cameraToCenterDistance = 0.5 / Math.tan(halfFov) * this.height;\n this._pixelPerMeter = mercatorZfromAltitude(1, this.center.lat) * this.worldSize;\n\n let m = mat4.identity(new Float64Array(16) as any);\n mat4.scale(m, m, [this.width / 2, -this.height / 2, 1]);\n mat4.translate(m, m, [1, -1, 0]);\n this.labelPlaneMatrix = m;\n\n m = mat4.identity(new Float64Array(16) as any);\n mat4.scale(m, m, [1, -1, 1]);\n mat4.translate(m, m, [-1, -1, 0]);\n mat4.scale(m, m, [2 / this.width, 2 / this.height, 1]);\n this.glCoordMatrix = m;\n\n // Calculate the camera to sea-level distance in pixel in respect of terrain\n const cameraToSeaLevelDistance = this.cameraToCenterDistance + this._elevation * this._pixelPerMeter / Math.cos(this._pitch);\n // In case of negative minimum elevation (e.g. the dead see, under the sea maps) use a lower plane for calculation\n const minElevation = Math.min(this.elevation, this.minElevationForCurrentTile);\n const cameraToLowestPointDistance = cameraToSeaLevelDistance - minElevation * this._pixelPerMeter / Math.cos(this._pitch);\n const lowestPlane = minElevation < 0 ? cameraToLowestPointDistance : cameraToSeaLevelDistance;\n\n // Find the distance from the center point [width/2 + offset.x, height/2 + offset.y] to the\n // center top point [width/2 + offset.x, 0] in Z units, using the law of sines.\n // 1 Z unit is equivalent to 1 horizontal px at the center of the map\n // (the distance between[width/2, height/2] and [width/2 + 1, height/2])\n const groundAngle = Math.PI / 2 + this._pitch;\n const fovAboveCenter = this._fov * (0.5 + offset.y / this.height);\n const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * lowestPlane / Math.sin(clamp(Math.PI - groundAngle - fovAboveCenter, 0.01, Math.PI - 0.01));\n\n // Find the distance from the center point to the horizon\n const horizon = this.getHorizon();\n const horizonAngle = Math.atan(horizon / this.cameraToCenterDistance);\n const fovCenterToHorizon = 2 * horizonAngle * (0.5 + offset.y / (horizon * 2));\n const topHalfSurfaceDistanceHorizon = Math.sin(fovCenterToHorizon) * lowestPlane / Math.sin(clamp(Math.PI - groundAngle - fovCenterToHorizon, 0.01, Math.PI - 0.01));\n\n // Calculate z distance of the farthest fragment that should be rendered.\n // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance`\n const topHalfMinDistance = Math.min(topHalfSurfaceDistance, topHalfSurfaceDistanceHorizon);\n this.farZ = (Math.cos(Math.PI / 2 - this._pitch) * topHalfMinDistance + lowestPlane) * 1.01;\n\n // The larger the value of nearZ is\n // - the more depth precision is available for features (good)\n // - clipping starts appearing sooner when the camera is close to 3d features (bad)\n //\n // Other values work for mapbox-gl-js but deck.gl was encountering precision issues\n // when rendering custom layers. This value was experimentally chosen and\n // seems to solve z-fighting issues in deck.gl while not clipping buildings too close to the camera.\n this.nearZ = this.height / 50;\n\n // matrix for conversion from location to clip space(-1 .. 1)\n m = new Float64Array(16) as any;\n mat4.perspective(m, this._fov, this.width / this.height, this.nearZ, this.farZ);\n\n // Apply center of perspective offset\n m[8] = -offset.x * 2 / this.width;\n m[9] = offset.y * 2 / this.height;\n this.projectionMatrix = mat4.clone(m);\n\n mat4.scale(m, m, [1, -1, 1]);\n mat4.translate(m, m, [0, 0, -this.cameraToCenterDistance]);\n mat4.rotateX(m, m, this._pitch);\n mat4.rotateZ(m, m, this.angle);\n mat4.translate(m, m, [-x, -y, 0]);\n\n // The mercatorMatrix can be used to transform points from mercator coordinates\n // ([0, 0] nw, [1, 1] se) to clip space.\n this.mercatorMatrix = mat4.scale([] as any, m, [this.worldSize, this.worldSize, this.worldSize]);\n\n // scale vertically to meters per pixel (inverse of ground resolution):\n mat4.scale(m, m, [1, 1, this._pixelPerMeter]);\n\n // matrix for conversion from world space to screen coordinates in 2D\n this.pixelMatrix = mat4.multiply(new Float64Array(16) as any, this.labelPlaneMatrix, m);\n\n // matrix for conversion from world space to clip space (-1 .. 1)\n mat4.translate(m, m, [0, 0, -this.elevation]); // elevate camera over terrain\n this.modelViewProjectionMatrix = m;\n this.invModelViewProjectionMatrix = mat4.invert([] as any, m);\n\n // create a fog matrix, same es proj-matrix but with near clipping-plane in mapcenter\n // needed to calculate a correct z-value for fog calculation, because projMatrix z value is not\n this.fogMatrix = new Float64Array(16) as any;\n mat4.perspective(this.fogMatrix, this._fov, this.width / this.height, cameraToSeaLevelDistance, this.farZ);\n this.fogMatrix[8] = -offset.x * 2 / this.width;\n this.fogMatrix[9] = offset.y * 2 / this.height;\n mat4.scale(this.fogMatrix, this.fogMatrix, [1, -1, 1]);\n mat4.translate(this.fogMatrix, this.fogMatrix, [0, 0, -this.cameraToCenterDistance]);\n mat4.rotateX(this.fogMatrix, this.fogMatrix, this._pitch);\n mat4.rotateZ(this.fogMatrix, this.fogMatrix, this.angle);\n mat4.translate(this.fogMatrix, this.fogMatrix, [-x, -y, 0]);\n mat4.scale(this.fogMatrix, this.fogMatrix, [1, 1, this._pixelPerMeter]);\n mat4.translate(this.fogMatrix, this.fogMatrix, [0, 0, -this.elevation]); // elevate camera over terrain\n\n // matrix for conversion from world space to screen coordinates in 3D\n this.pixelMatrix3D = mat4.multiply(new Float64Array(16) as any, this.labelPlaneMatrix, m);\n\n // Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles.\n // We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional\n // coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension\n // is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle\n // of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that\n // it is always <= 0.5 pixels.\n const xShift = (this.width % 2) / 2, yShift = (this.height % 2) / 2,\n angleCos = Math.cos(this.angle), angleSin = Math.sin(this.angle),\n dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift,\n dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift;\n const alignedM = new Float64Array(m) as any as mat4;\n mat4.translate(alignedM, alignedM, [dx > 0.5 ? dx - 1 : dx, dy > 0.5 ? dy - 1 : dy, 0]);\n this.alignedModelViewProjectionMatrix = alignedM;\n\n // inverse matrix for conversion from screen coordinates to location\n m = mat4.invert(new Float64Array(16) as any, this.pixelMatrix);\n if (!m) throw new Error('failed to invert matrix');\n this.pixelMatrixInverse = m;\n\n this._posMatrixCache = {};\n this._alignedPosMatrixCache = {};\n this._fogMatrixCache = {};\n }\n\n maxPitchScaleFactor() {\n // calcMatrices hasn't run yet\n if (!this.pixelMatrixInverse) return 1;\n\n const coord = this.pointCoordinate(new Point(0, 0));\n const p = [coord.x * this.worldSize, coord.y * this.worldSize, 0, 1] as vec4;\n const topPoint = vec4.transformMat4(p, p, this.pixelMatrix);\n return topPoint[3] / this.cameraToCenterDistance;\n }\n\n /**\n * The camera looks at the map from a 3D (lng, lat, altitude) location. Let's use `cameraLocation`\n * as the name for the location under the camera and on the surface of the earth (lng, lat, 0).\n * `cameraPoint` is the projected position of the `cameraLocation`.\n *\n * This point is useful to us because only fill-extrusions that are between `cameraPoint` and\n * the query point on the surface of the earth can extend and intersect the query.\n *\n * When the map is not pitched the `cameraPoint` is equivalent to the center of the map because\n * the camera is right above the center of the map.\n */\n getCameraPoint() {\n const pitch = this._pitch;\n const yOffset = Math.tan(pitch) * (this.cameraToCenterDistance || 1);\n return this.centerPoint.add(new Point(0, yOffset));\n }\n\n /**\n * When the map is pitched, some of the 3D features that intersect a query will not intersect\n * the query at the surface of the earth. Instead the feature may be closer and only intersect\n * the query because it extrudes into the air.\n * @param queryGeometry - For point queries, the line from the query point to the \"camera point\",\n * for other geometries, the envelope of the query geometry and the \"camera point\"\n * @returns a geometry that includes all of the original query as well as all possible ares of the\n * screen where the *base* of a visible extrusion could be.\n *\n */\n getCameraQueryGeometry(queryGeometry: Array): Array {\n const c = this.getCameraPoint();\n\n if (queryGeometry.length === 1) {\n return [queryGeometry[0], c];\n } else {\n let minX = c.x;\n let minY = c.y;\n let maxX = c.x;\n let maxY = c.y;\n for (const p of queryGeometry) {\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x);\n maxY = Math.max(maxY, p.y);\n }\n return [\n new Point(minX, minY),\n new Point(maxX, minY),\n new Point(maxX, maxY),\n new Point(minX, maxY),\n new Point(minX, minY)\n ];\n }\n }\n /**\n * Return the distance to the camera in clip space from a LngLat.\n * This can be compared to the value from the depth buffer (terrain.depthAtPoint)\n * to determine whether a point is occluded.\n * @param lngLat - the point\n * @param elevation - the point's elevation\n * @returns depth value in clip space (between 0 and 1)\n */\n lngLatToCameraDepth(lngLat: LngLat, elevation: number) {\n const coord = this.locationCoordinate(lngLat);\n const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation, 1] as vec4;\n vec4.transformMat4(p, p, this.modelViewProjectionMatrix);\n return (p[2] / p[3]);\n }\n}\n","import * as glMatrix from \"./common.js\";\n/**\n * 2x2 Matrix\n * @module mat2\n */\n\n/**\n * Creates a new identity mat2\n *\n * @returns {mat2} a new 2x2 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n }\n\n out[0] = 1;\n out[3] = 1;\n return out;\n}\n/**\n * Creates a new mat2 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat2} a matrix to clone\n * @returns {mat2} a new 2x2 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Copy the values from one mat2 to another\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the source matrix\n * @returns {mat2} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Set a mat2 to the identity matrix\n *\n * @param {mat2} out the receiving matrix\n * @returns {mat2} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n}\n/**\n * Create a new mat2 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m10 Component in column 1, row 0 position (index 2)\n * @param {Number} m11 Component in column 1, row 1 position (index 3)\n * @returns {mat2} out A new 2x2 matrix\n */\n\nexport function fromValues(m00, m01, m10, m11) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = m00;\n out[1] = m01;\n out[2] = m10;\n out[3] = m11;\n return out;\n}\n/**\n * Set the components of a mat2 to the given values\n *\n * @param {mat2} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m10 Component in column 1, row 0 position (index 2)\n * @param {Number} m11 Component in column 1, row 1 position (index 3)\n * @returns {mat2} out\n */\n\nexport function set(out, m00, m01, m10, m11) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m10;\n out[3] = m11;\n return out;\n}\n/**\n * Transpose the values of a mat2\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the source matrix\n * @returns {mat2} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache\n // some values\n if (out === a) {\n var a1 = a[1];\n out[1] = a[2];\n out[2] = a1;\n } else {\n out[0] = a[0];\n out[1] = a[2];\n out[2] = a[1];\n out[3] = a[3];\n }\n\n return out;\n}\n/**\n * Inverts a mat2\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the source matrix\n * @returns {mat2} out\n */\n\nexport function invert(out, a) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3]; // Calculate the determinant\n\n var det = a0 * a3 - a2 * a1;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = a3 * det;\n out[1] = -a1 * det;\n out[2] = -a2 * det;\n out[3] = a0 * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat2\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the source matrix\n * @returns {mat2} out\n */\n\nexport function adjoint(out, a) {\n // Caching this value is nessecary if out == a\n var a0 = a[0];\n out[0] = a[3];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = a0;\n return out;\n}\n/**\n * Calculates the determinant of a mat2\n *\n * @param {ReadonlyMat2} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n return a[0] * a[3] - a[2] * a[1];\n}\n/**\n * Multiplies two mat2's\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the first operand\n * @param {ReadonlyMat2} b the second operand\n * @returns {mat2} out\n */\n\nexport function multiply(out, a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n out[0] = a0 * b0 + a2 * b1;\n out[1] = a1 * b0 + a3 * b1;\n out[2] = a0 * b2 + a2 * b3;\n out[3] = a1 * b2 + a3 * b3;\n return out;\n}\n/**\n * Rotates a mat2 by the given angle\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat2} out\n */\n\nexport function rotate(out, a, rad) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n out[0] = a0 * c + a2 * s;\n out[1] = a1 * c + a3 * s;\n out[2] = a0 * -s + a2 * c;\n out[3] = a1 * -s + a3 * c;\n return out;\n}\n/**\n * Scales the mat2 by the dimensions in the given vec2\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the matrix to rotate\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat2} out\n **/\n\nexport function scale(out, a, v) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var v0 = v[0],\n v1 = v[1];\n out[0] = a0 * v0;\n out[1] = a1 * v0;\n out[2] = a2 * v1;\n out[3] = a3 * v1;\n return out;\n}\n/**\n * Creates a matrix from a given angle\n * This is equivalent to (but much faster than):\n *\n * mat2.identity(dest);\n * mat2.rotate(dest, dest, rad);\n *\n * @param {mat2} out mat2 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat2} out\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = -s;\n out[3] = c;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat2.identity(dest);\n * mat2.scale(dest, dest, vec);\n *\n * @param {mat2} out mat2 receiving operation result\n * @param {ReadonlyVec2} v Scaling vector\n * @returns {mat2} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = v[1];\n return out;\n}\n/**\n * Returns a string representation of a mat2\n *\n * @param {ReadonlyMat2} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat2(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat2\n *\n * @param {ReadonlyMat2} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3]);\n}\n/**\n * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix\n * @param {ReadonlyMat2} L the lower triangular matrix\n * @param {ReadonlyMat2} D the diagonal matrix\n * @param {ReadonlyMat2} U the upper triangular matrix\n * @param {ReadonlyMat2} a the input matrix to factorize\n */\n\nexport function LDU(L, D, U, a) {\n L[2] = a[2] / a[0];\n U[0] = a[0];\n U[1] = a[1];\n U[3] = a[3] - L[2] * U[1];\n return [L, D, U];\n}\n/**\n * Adds two mat2's\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the first operand\n * @param {ReadonlyMat2} b the second operand\n * @returns {mat2} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the first operand\n * @param {ReadonlyMat2} b the second operand\n * @returns {mat2} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat2} a The first matrix.\n * @param {ReadonlyMat2} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat2} a The first matrix.\n * @param {ReadonlyMat2} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat2} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n/**\n * Adds two mat2's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat2} out the receiving vector\n * @param {ReadonlyMat2} a the first operand\n * @param {ReadonlyMat2} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat2} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n/**\n * Alias for {@link mat2.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat2.subtract}\n * @function\n */\n\nexport var sub = subtract;","/**\n * Throttle the given function to run at most every `period` milliseconds.\n */\nexport function throttle void>(fn: T, time: number): (...args: Parameters) => ReturnType {\n let pending = false;\n let timerId: ReturnType = null;\n let lastCallContext = null;\n let lastCallArgs: Parameters;\n\n const later = () => {\n timerId = null;\n if (pending) {\n fn.apply(lastCallContext, lastCallArgs);\n timerId = setTimeout(later, time);\n pending = false;\n }\n };\n\n return (...args: Parameters) => {\n pending = true;\n lastCallContext = this;\n lastCallArgs = args;\n if (!timerId) {\n later();\n }\n return timerId;\n };\n}\n","import {throttle} from '../util/throttle';\n\nimport type {Map} from './map';\n\n/**\n * Adds the map's position to its page's location hash.\n * Passed as an option to the map object.\n *\n * @group Markers and Controls\n */\nexport class Hash {\n _map: Map;\n _hashName: string;\n\n constructor(hashName?: string | null) {\n this._hashName = hashName && encodeURIComponent(hashName);\n }\n\n /**\n * Map element to listen for coordinate changes\n *\n * @param map - The map object\n */\n addTo(map: Map) {\n this._map = map;\n addEventListener('hashchange', this._onHashChange, false);\n this._map.on('moveend', this._updateHash);\n return this;\n }\n\n /**\n * Removes hash\n */\n remove() {\n removeEventListener('hashchange', this._onHashChange, false);\n this._map.off('moveend', this._updateHash);\n clearTimeout(this._updateHash());\n this._removeHash();\n\n delete this._map;\n return this;\n }\n\n getHashString(mapFeedback?: boolean) {\n const center = this._map.getCenter(),\n zoom = Math.round(this._map.getZoom() * 100) / 100,\n // derived from equation: 512px * 2^z / 360 / 10^d < 0.5px\n precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10),\n m = Math.pow(10, precision),\n lng = Math.round(center.lng * m) / m,\n lat = Math.round(center.lat * m) / m,\n bearing = this._map.getBearing(),\n pitch = this._map.getPitch();\n let hash = '';\n if (mapFeedback) {\n // new map feedback site has some constraints that don't allow\n // us to use the same hash format as we do for the Map hash option.\n hash += `/${lng}/${lat}/${zoom}`;\n } else {\n hash += `${zoom}/${lat}/${lng}`;\n }\n\n if (bearing || pitch) hash += (`/${Math.round(bearing * 10) / 10}`);\n if (pitch) hash += (`/${Math.round(pitch)}`);\n\n if (this._hashName) {\n const hashName = this._hashName;\n let found = false;\n const parts = window.location.hash.slice(1).split('&').map(part => {\n const key = part.split('=')[0];\n if (key === hashName) {\n found = true;\n return `${key}=${hash}`;\n }\n return part;\n }).filter(a => a);\n if (!found) {\n parts.push(`${hashName}=${hash}`);\n }\n return `#${parts.join('&')}`;\n }\n\n return `#${hash}`;\n }\n\n _getCurrentHash = () => {\n // Get the current hash from location, stripped from its number sign\n const hash = window.location.hash.replace('#', '');\n if (this._hashName) {\n // Split the parameter-styled hash into parts and find the value we need\n let keyval;\n hash.split('&').map(\n part => part.split('=')\n ).forEach(part => {\n if (part[0] === this._hashName) {\n keyval = part;\n }\n });\n return (keyval ? keyval[1] || '' : '').split('/');\n }\n return hash.split('/');\n };\n\n _onHashChange = () => {\n const loc = this._getCurrentHash();\n if (loc.length >= 3 && !loc.some(v => isNaN(v))) {\n const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(loc[3] || 0) : this._map.getBearing();\n this._map.jumpTo({\n center: [+loc[2], +loc[1]],\n zoom: +loc[0],\n bearing,\n pitch: +(loc[4] || 0)\n });\n return true;\n }\n return false;\n };\n\n _updateHashUnthrottled = () => {\n // Replace if already present, else append the updated hash string\n const location = window.location.href.replace(/(#.*)?$/, this.getHashString());\n window.history.replaceState(window.history.state, null, location);\n };\n\n _removeHash = () => {\n const currentHash = this._getCurrentHash();\n if (currentHash.length === 0) {\n return;\n }\n const baseHash = currentHash.join('/');\n let targetHash = baseHash;\n if (targetHash.split('&').length > 0) {\n targetHash = targetHash.split('&')[0]; // #3/1/2&foo=bar -> #3/1/2\n }\n if (this._hashName) {\n targetHash = `${this._hashName}=${baseHash}`;\n }\n let replaceString = window.location.hash.replace(targetHash, '');\n if (replaceString.startsWith('#&')) {\n replaceString = replaceString.slice(0, 1) + replaceString.slice(2);\n } else if (replaceString === '#') {\n replaceString = '';\n }\n let location = window.location.href.replace(/(#.+)?$/, replaceString);\n location = location.replace('&&', '&');\n window.history.replaceState(window.history.state, null, location);\n };\n\n /**\n * Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds.\n */\n _updateHash: () => ReturnType = throttle(this._updateHashUnthrottled, 30 * 1000 / 100);\n}\n","import {browser} from '../util/browser';\nimport type {Map} from './map';\nimport {bezier, clamp, extend} from '../util/util';\nimport Point from '@mapbox/point-geometry';\nimport type {DragPanOptions} from './handler/shim/drag_pan';\n\nconst defaultInertiaOptions = {\n linearity: 0.3,\n easing: bezier(0, 0, 0.3, 1),\n};\n\nconst defaultPanInertiaOptions = extend({\n deceleration: 2500,\n maxSpeed: 1400\n}, defaultInertiaOptions);\n\nconst defaultZoomInertiaOptions = extend({\n deceleration: 20,\n maxSpeed: 1400\n}, defaultInertiaOptions);\n\nconst defaultBearingInertiaOptions = extend({\n deceleration: 1000,\n maxSpeed: 360\n}, defaultInertiaOptions);\n\nconst defaultPitchInertiaOptions = extend({\n deceleration: 1000,\n maxSpeed: 90\n}, defaultInertiaOptions);\n\nexport type InertiaOptions = {\n linearity: number;\n easing: (t: number) => number;\n deceleration: number;\n maxSpeed: number;\n};\n\nexport class HandlerInertia {\n _map: Map;\n _inertiaBuffer: Array<{\n time: number;\n settings: any;\n }>;\n\n constructor(map: Map) {\n this._map = map;\n this.clear();\n }\n\n clear() {\n this._inertiaBuffer = [];\n }\n\n record(settings: any) {\n this._drainInertiaBuffer();\n this._inertiaBuffer.push({time: browser.now(), settings});\n }\n\n _drainInertiaBuffer() {\n const inertia = this._inertiaBuffer,\n now = browser.now(),\n cutoff = 160; //msec\n\n while (inertia.length > 0 && now - inertia[0].time > cutoff)\n inertia.shift();\n }\n\n _onMoveEnd(panInertiaOptions?: DragPanOptions | boolean) {\n this._drainInertiaBuffer();\n if (this._inertiaBuffer.length < 2) {\n return;\n }\n\n const deltas = {\n zoom: 0,\n bearing: 0,\n pitch: 0,\n pan: new Point(0, 0),\n pinchAround: undefined,\n around: undefined\n };\n\n for (const {settings} of this._inertiaBuffer) {\n deltas.zoom += settings.zoomDelta || 0;\n deltas.bearing += settings.bearingDelta || 0;\n deltas.pitch += settings.pitchDelta || 0;\n if (settings.panDelta) deltas.pan._add(settings.panDelta);\n if (settings.around) deltas.around = settings.around;\n if (settings.pinchAround) deltas.pinchAround = settings.pinchAround;\n }\n\n const lastEntry = this._inertiaBuffer[this._inertiaBuffer.length - 1];\n const duration = (lastEntry.time - this._inertiaBuffer[0].time);\n\n const easeOptions = {} as any;\n\n if (deltas.pan.mag()) {\n const result = calculateEasing(deltas.pan.mag(), duration, extend({}, defaultPanInertiaOptions, panInertiaOptions || {}));\n easeOptions.offset = deltas.pan.mult(result.amount / deltas.pan.mag());\n easeOptions.center = this._map.transform.center;\n extendDuration(easeOptions, result);\n }\n\n if (deltas.zoom) {\n const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions);\n easeOptions.zoom = this._map.transform.zoom + result.amount;\n extendDuration(easeOptions, result);\n }\n\n if (deltas.bearing) {\n const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions);\n easeOptions.bearing = this._map.transform.bearing + clamp(result.amount, -179, 179);\n extendDuration(easeOptions, result);\n }\n\n if (deltas.pitch) {\n const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions);\n easeOptions.pitch = this._map.transform.pitch + result.amount;\n extendDuration(easeOptions, result);\n }\n\n if (easeOptions.zoom || easeOptions.bearing) {\n const last = deltas.pinchAround === undefined ? deltas.around : deltas.pinchAround;\n easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter();\n }\n\n this.clear();\n return extend(easeOptions, {\n noMoveStart: true\n });\n\n }\n}\n\n// Unfortunately zoom, bearing, etc can't have different durations and easings so\n// we need to choose one. We use the longest duration and it's corresponding easing.\nfunction extendDuration(easeOptions, result) {\n if (!easeOptions.duration || easeOptions.duration < result.duration) {\n easeOptions.duration = result.duration;\n easeOptions.easing = result.easing;\n }\n}\n\nfunction calculateEasing(amount, inertiaDuration: number, inertiaOptions) {\n const {maxSpeed, linearity, deceleration} = inertiaOptions;\n const speed = clamp(\n amount * linearity / (inertiaDuration / 1000),\n -maxSpeed,\n maxSpeed);\n const duration = Math.abs(speed) / (deceleration * linearity);\n return {\n easing: inertiaOptions.easing,\n duration: duration * 1000,\n amount: speed * (duration / 2)\n };\n}\n","import {Event} from '../util/evented';\n\nimport {DOM} from '../util/dom';\nimport Point from '@mapbox/point-geometry';\nimport {extend} from '../util/util';\nimport type {MapGeoJSONFeature} from '../util/vectortile_to_geojson';\n\nimport type {Map} from './map';\nimport type {LngLat} from '../geo/lng_lat';\nimport type {SourceSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * An event from the mouse relevant to a specific layer.\n *\n * @group Event Related\n */\nexport type MapLayerMouseEvent = MapMouseEvent & { features?: MapGeoJSONFeature[] };\n\n/**\n * An event from a touch device relevant to a specific layer.\n *\n * @group Event Related\n */\nexport type MapLayerTouchEvent = MapTouchEvent & { features?: MapGeoJSONFeature[] };\n\n/**\n * The source event data type\n */\nexport type MapSourceDataType = 'content' | 'metadata' | 'visibility' | 'idle';\n\n/**\n * `MapLayerEventType` - a mapping between the event name and the event.\n * **Note:** These events are compatible with the optional `layerId` parameter.\n * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the\n * event action contains a visible portion of the specified layer.\n * The following example can be used for all the events.\n *\n * @group Event Related\n * @example\n * ```ts\n * // Initialize the map\n * let map = new Map({ // map options });\n * // Set an event listener for a specific layer\n * map.on('the-event-name', 'poi-label', (e) => {\n * console.log('An event has occurred on a visible portion of the poi-label layer');\n * });\n * ```\n */\nexport type MapLayerEventType = {\n /**\n * Fired when a pointing device (usually a mouse) is pressed and released contains a visible portion of the specified layer.\n *\n * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure/)\n * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/)\n */\n click: MapLayerMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is pressed and released twice contains a visible portion of the specified layer.\n *\n * **Note:** Under normal conditions, this event will be preceded by two `click` events.\n */\n dblclick: MapLayerMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is pressed while inside a visible portion of the specified layer.\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n mousedown: MapLayerMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is released while inside a visible portion of the specified layer.\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n mouseup: MapLayerMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is moved while the cursor is inside a visible portion of the specified layer.\n * As you move the cursor across the layer, the event will fire every time the cursor changes position within that layer.\n *\n * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/)\n * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/)\n * @see [Display a popup on over](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/)\n */\n mousemove: MapLayerMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) enters a visible portion of a specified layer from\n * outside that layer or outside the map canvas.\n *\n * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/)\n * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/)\n */\n mouseenter: MapLayerMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves\n * the map canvas.\n *\n * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/)\n * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/)\n */\n mouseleave: MapLayerMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is moved inside a visible portion of the specified layer.\n *\n * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/)\n * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/)\n * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/)\n */\n mouseover: MapLayerMouseEvent;\n /**\n * Fired when a point device (usually a mouse) leaves the visible portion of the specified layer.\n */\n mouseout: MapLayerMouseEvent;\n /**\n * Fired when the right button of the mouse is clicked or the context menu key is pressed within visible portion of the specified layer.\n */\n contextmenu: MapLayerMouseEvent;\n /**\n * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the visible portion of the specified layer.\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n touchstart: MapLayerTouchEvent;\n /**\n * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the visible portion of the specified layer.\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n touchend: MapLayerTouchEvent;\n /**\n * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the visible portion of the specified layer.\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n touchcancel: MapLayerTouchEvent;\n};\n\n/**\n * `MapEventType` - a mapping between the event name and the event value.\n * These events are used with the {@link Map#on} method.\n * When using a `layerId` with {@link Map#on} method, please refer to {@link MapLayerEventType}.\n * The following example can be used for all the events.\n *\n * @group Event Related\n * @example\n * ```ts\n * // Initialize the map\n * let map = new Map({ // map options });\n * // Set an event listener\n * map.on('the-event-name', () => {\n * console.log('An event has occurred!');\n * });\n * ```\n */\nexport type MapEventType = {\n /**\n * Fired when an error occurs. This is GL JS's primary error reporting\n * mechanism. We use an event instead of `throw` to better accommodate\n * asynchronous operations. If no listeners are bound to the `error` event, the\n * error will be printed to the console.\n */\n error: ErrorEvent;\n /**\n * Fired immediately after all necessary resources have been downloaded\n * and the first visually complete rendering of the map has occurred.\n *\n * @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-markers/)\n * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/)\n * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-point-along-line/)\n */\n load: MapLibreEvent;\n /**\n * Fired after the last frame rendered before the map enters an\n * \"idle\" state:\n *\n * - No camera transitions are in progress\n * - All currently requested tiles have loaded\n * - All fade/transition animations have completed\n */\n idle: MapLibreEvent;\n /**\n * Fired immediately after the map has been removed with {@link Map#remove}.\n */\n remove: MapLibreEvent;\n /**\n * Fired whenever the map is drawn to the screen, as the result of\n *\n * - a change to the map's position, zoom, pitch, or bearing\n * - a change to the map's style\n * - a change to a GeoJSON source\n * - the loading of a vector tile, GeoJSON file, glyph, or sprite\n */\n render: MapLibreEvent;\n /**\n * Fired immediately after the map has been resized.\n */\n resize: MapLibreEvent;\n /**\n * Fired when the WebGL context is lost.\n */\n webglcontextlost: MapContextEvent;\n /**\n * Fired when the WebGL context is restored.\n */\n webglcontextrestored: MapContextEvent;\n /**\n * Fired when any map data (style, source, tile, etc) begins loading or\n * changing asynchronously. All `dataloading` events are followed by a `data`,\n * `dataabort` or `error` event.\n */\n dataloading: MapDataEvent;\n /**\n * Fired when any map data loads or changes. See {@link MapDataEvent} for more information.\n * @see [Display HTML clusters with custom properties](https://maplibre.org/maplibre-gl-js/docs/examples/cluster-html/)\n */\n data: MapDataEvent;\n tiledataloading: MapDataEvent;\n /**\n * Fired when one of the map's sources begins loading or changing asynchronously.\n * All `sourcedataloading` events are followed by a `sourcedata`, `sourcedataabort` or `error` event.\n */\n sourcedataloading: MapSourceDataEvent;\n /**\n * Fired when the map's style begins loading or changing asynchronously.\n * All `styledataloading` events are followed by a `styledata`\n * or `error` event.\n */\n styledataloading: MapStyleDataEvent;\n /**\n * Fired when one of the map's sources loads or changes, including if a tile belonging\n * to a source loads or changes.\n */\n sourcedata: MapSourceDataEvent;\n /**\n * Fired when the map's style loads or changes.\n */\n styledata: MapStyleDataEvent;\n /**\n * Fired when an icon or pattern needed by the style is missing. The missing image can\n * be added with {@link Map#addImage} within this event listener callback to prevent the image from\n * being skipped. This event can be used to dynamically generate icons and patterns.\n * @see [Generate and add a missing icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-missing-generated/)\n */\n styleimagemissing: MapStyleImageMissingEvent;\n /**\n * Fired when a request for one of the map's sources' tiles or data is aborted.\n */\n dataabort: MapDataEvent;\n /**\n * Fired when a request for one of the map's sources' data is aborted.\n */\n sourcedataabort: MapSourceDataEvent;\n /**\n * Fired when the user cancels a \"box zoom\" interaction, or when the bounding box does not meet the minimum size threshold.\n * See {@link BoxZoomHandler}.\n */\n boxzoomcancel: MapLibreZoomEvent;\n /**\n * Fired when a \"box zoom\" interaction starts. See {@link BoxZoomHandler}.\n */\n boxzoomstart: MapLibreZoomEvent;\n /**\n * Fired when a \"box zoom\" interaction ends. See {@link BoxZoomHandler}.\n */\n boxzoomend: MapLibreZoomEvent;\n /**\n * Fired when a [`touchcancel`](https://developer.mozilla.org/en-US/docs/Web/Events/touchcancel) event occurs within the map.\n */\n touchcancel: MapTouchEvent;\n /**\n * Fired when a [`touchmove`](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event occurs within the map.\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n touchmove: MapTouchEvent;\n /**\n * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the map.\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n touchend: MapTouchEvent;\n /**\n * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the map.\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n touchstart: MapTouchEvent;\n /**\n * Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map.\n *\n * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure/)\n * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/)\n */\n click: MapMouseEvent;\n /**\n * Fired when the right button of the mouse is clicked or the context menu key is pressed within the map.\n */\n contextmenu: MapMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is pressed and released twice at the same point on the map in rapid succession.\n *\n * **Note:** Under normal conditions, this event will be preceded by two `click` events.\n */\n dblclick: MapMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is moved while the cursor is inside the map.\n * As you move the cursor across the map, the event will fire every time the cursor changes position within the map.\n *\n * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/)\n * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/)\n * @see [Display a popup on over](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/)\n */\n mousemove: MapMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is released within the map.\n *\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n mouseup: MapMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is pressed within the map.\n *\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n mousedown: MapMouseEvent;\n /**\n * Fired when a point device (usually a mouse) leaves the map's canvas.\n */\n mouseout: MapMouseEvent;\n /**\n * Fired when a pointing device (usually a mouse) is moved within the map.\n * As you move the cursor across a web page containing a map,\n * the event will fire each time it enters the map or any child elements.\n *\n * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/)\n * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/)\n * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/)\n */\n mouseover: MapMouseEvent;\n /**\n * Fired just before the map begins a transition from one\n * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}.\n *\n */\n movestart: MapLibreEvent;\n /**\n * Fired repeatedly during an animated transition from one view to\n * another, as the result of either user interaction or methods such as {@link Map#flyTo}.\n *\n * @see [Display HTML clusters with custom properties](https://maplibre.org/maplibre-gl-js/docs/examples/cluster-html/)\n */\n move: MapLibreEvent;\n /**\n * Fired just after the map completes a transition from one\n * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}.\n *\n * @see [Display HTML clusters with custom properties](https://maplibre.org/maplibre-gl-js/docs/examples/cluster-html/)\n */\n moveend: MapLibreEvent;\n /**\n * Fired just before the map begins a transition from one zoom level to another,\n * as the result of either user interaction or methods such as {@link Map#flyTo}.\n */\n zoomstart: MapLibreEvent;\n /**\n * Fired repeatedly during an animated transition from one zoom level to another,\n * as the result of either user interaction or methods such as {@link Map#flyTo}.\n */\n zoom: MapLibreEvent;\n /**\n * Fired just after the map completes a transition from one zoom level to another,\n * as the result of either user interaction or methods such as {@link Map#flyTo}.\n */\n zoomend: MapLibreEvent;\n /**\n * Fired when a \"drag to rotate\" interaction starts. See {@link DragRotateHandler}.\n */\n rotatestart: MapLibreEvent;\n /**\n * Fired repeatedly during a \"drag to rotate\" interaction. See {@link DragRotateHandler}.\n */\n rotate: MapLibreEvent;\n /**\n * Fired when a \"drag to rotate\" interaction ends. See {@link DragRotateHandler}.\n */\n rotateend: MapLibreEvent;\n /**\n * Fired when a \"drag to pan\" interaction starts. See {@link DragPanHandler}.\n */\n dragstart: MapLibreEvent;\n /**\n * Fired repeatedly during a \"drag to pan\" interaction. See {@link DragPanHandler}.\n */\n drag: MapLibreEvent;\n /**\n * Fired when a \"drag to pan\" interaction ends. See {@link DragPanHandler}.\n * @see [Create a draggable marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/)\n */\n dragend: MapLibreEvent;\n /**\n * Fired whenever the map's pitch (tilt) begins a change as\n * the result of either user interaction or methods such as {@link Map#flyTo} .\n */\n pitchstart: MapLibreEvent;\n /**\n * Fired repeatedly during the map's pitch (tilt) animation between\n * one state and another as the result of either user interaction\n * or methods such as {@link Map#flyTo}.\n */\n pitch: MapLibreEvent;\n /**\n * Fired immediately after the map's pitch (tilt) finishes changing as\n * the result of either user interaction or methods such as {@link Map#flyTo}.\n */\n pitchend: MapLibreEvent;\n /**\n * Fired when a [`wheel`](https://developer.mozilla.org/en-US/docs/Web/Events/wheel) event occurs within the map.\n */\n wheel: MapWheelEvent;\n /**\n * Fired when terrain is changed\n */\n terrain: MapTerrainEvent;\n /**\n * Fired whenever the cooperativeGestures option prevents a gesture from being handled by the map.\n * This is useful for showing your own UI when this happens.\n */\n cooperativegestureprevented: MapLibreEvent & {\n gestureType: 'wheel_zoom' | 'touch_pan';\n };\n};\n\n/**\n * The base event for MapLibre\n *\n * @group Event Related\n */\nexport type MapLibreEvent = {\n type: keyof MapEventType | keyof MapLayerEventType;\n target: Map;\n originalEvent: TOrig;\n}\n\n/**\n * The style data event\n *\n * @group Event Related\n */\nexport type MapStyleDataEvent = MapLibreEvent & {\n dataType: 'style';\n}\n\n/**\n * The source data event interface\n *\n * @group Event Related\n */\nexport type MapSourceDataEvent = MapLibreEvent & {\n dataType: 'source';\n /**\n * True if the event has a `dataType` of `source` and the source has no outstanding network requests.\n */\n isSourceLoaded: boolean;\n /**\n * The [style spec representation of the source](https://maplibre.org/maplibre-style-spec/#sources) if the event has a `dataType` of `source`.\n */\n source: SourceSpecification;\n sourceId: string;\n sourceDataType: MapSourceDataType;\n /**\n * The tile being loaded or changed, if the event has a `dataType` of `source` and\n * the event is related to loading of a tile.\n */\n tile: any;\n}\n/**\n * `MapMouseEvent` is the event type for mouse-related map events.\n *\n * @group Event Related\n *\n * @example\n * ```ts\n * // The `click` event is an example of a `MapMouseEvent`.\n * // Set up an event listener on the map.\n * map.on('click', (e) => {\n * // The event object (e) contains information like the\n * // coordinates of the point on the map that was clicked.\n * console.log('A click event has occurred at ' + e.lngLat);\n * });\n * ```\n */\nexport class MapMouseEvent extends Event implements MapLibreEvent {\n /**\n * The event type\n */\n type: 'mousedown' | 'mouseup' | 'click' | 'dblclick' | 'mousemove' | 'mouseover' | 'mouseenter' | 'mouseleave' | 'mouseout' | 'contextmenu';\n\n /**\n * The `Map` object that fired the event.\n */\n target: Map;\n\n /**\n * The DOM event which caused the map event.\n */\n originalEvent: MouseEvent;\n\n /**\n * The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner.\n */\n point: Point;\n\n /**\n * The geographic location on the map of the mouse cursor.\n */\n lngLat: LngLat;\n\n /**\n * Prevents subsequent default processing of the event by the map.\n *\n * Calling this method will prevent the following default map behaviors:\n *\n * * On `mousedown` events, the behavior of {@link DragPanHandler}\n * * On `mousedown` events, the behavior of {@link DragRotateHandler}\n * * On `mousedown` events, the behavior of {@link BoxZoomHandler}\n * * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler}\n *\n */\n preventDefault() {\n this._defaultPrevented = true;\n }\n\n /**\n * `true` if `preventDefault` has been called.\n */\n get defaultPrevented(): boolean {\n return this._defaultPrevented;\n }\n\n _defaultPrevented: boolean;\n\n constructor(type: string, map: Map, originalEvent: MouseEvent, data: any = {}) {\n const point = DOM.mousePos(map.getCanvas(), originalEvent);\n const lngLat = map.unproject(point);\n super(type, extend({point, lngLat, originalEvent}, data));\n this._defaultPrevented = false;\n this.target = map;\n }\n}\n\n/**\n * `MapTouchEvent` is the event type for touch-related map events.\n *\n * @group Event Related\n */\nexport class MapTouchEvent extends Event implements MapLibreEvent {\n /**\n * The event type.\n */\n type: 'touchstart' | 'touchmove' | 'touchend' | 'touchcancel';\n\n /**\n * The `Map` object that fired the event.\n */\n target: Map;\n\n /**\n * The DOM event which caused the map event.\n */\n originalEvent: TouchEvent;\n\n /**\n * The geographic location on the map of the center of the touch event points.\n */\n lngLat: LngLat;\n\n /**\n * The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left\n * corner.\n */\n point: Point;\n\n /**\n * The array of pixel coordinates corresponding to a\n * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property.\n */\n points: Array;\n\n /**\n * The geographical locations on the map corresponding to a\n * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property.\n */\n lngLats: Array;\n\n /**\n * Prevents subsequent default processing of the event by the map.\n *\n * Calling this method will prevent the following default map behaviors:\n *\n * * On `touchstart` events, the behavior of {@link DragPanHandler}\n * * On `touchstart` events, the behavior of {@link TwoFingersTouchZoomRotateHandler}\n *\n */\n preventDefault() {\n this._defaultPrevented = true;\n }\n\n /**\n * `true` if `preventDefault` has been called.\n */\n get defaultPrevented(): boolean {\n return this._defaultPrevented;\n }\n\n _defaultPrevented: boolean;\n\n constructor(type: string, map: Map, originalEvent: TouchEvent) {\n const touches = type === 'touchend' ? originalEvent.changedTouches : originalEvent.touches;\n const points = DOM.touchPos(map.getCanvasContainer(), touches);\n const lngLats = points.map((t) => map.unproject(t));\n const point = points.reduce((prev, curr, i, arr) => {\n return prev.add(curr.div(arr.length));\n }, new Point(0, 0));\n const lngLat = map.unproject(point);\n super(type, {points, point, lngLats, lngLat, originalEvent});\n this._defaultPrevented = false;\n }\n}\n\n/**\n * `MapWheelEvent` is the event type for the `wheel` map event.\n *\n * @group Event Related\n */\nexport class MapWheelEvent extends Event {\n /**\n * The event type.\n */\n type: 'wheel';\n\n /**\n * The `Map` object that fired the event.\n */\n target: Map;\n\n /**\n * The DOM event which caused the map event.\n */\n originalEvent: WheelEvent;\n\n /**\n * Prevents subsequent default processing of the event by the map.\n *\n * Calling this method will prevent the behavior of {@link ScrollZoomHandler}.\n */\n preventDefault() {\n this._defaultPrevented = true;\n }\n\n /**\n * `true` if `preventDefault` has been called.\n */\n get defaultPrevented(): boolean {\n return this._defaultPrevented;\n }\n\n _defaultPrevented: boolean;\n\n /** */\n constructor(type: string, map: Map, originalEvent: WheelEvent) {\n super(type, {originalEvent});\n this._defaultPrevented = false;\n }\n}\n\n/**\n * A `MapLibreZoomEvent` is the event type for the boxzoom-related map events emitted by the {@link BoxZoomHandler}.\n *\n * @group Event Related\n */\nexport type MapLibreZoomEvent = {\n /**\n * The type of boxzoom event. One of `boxzoomstart`, `boxzoomend` or `boxzoomcancel`\n */\n type: 'boxzoomstart' | 'boxzoomend' | 'boxzoomcancel';\n /**\n * The `Map` instance that triggered the event\n */\n target: Map;\n /**\n * The DOM event that triggered the boxzoom event. Can be a `MouseEvent` or `KeyboardEvent`\n */\n originalEvent: MouseEvent;\n};\n\n/**\n * A `MapDataEvent` object is emitted with the `data`\n * and `dataloading` events. Possible values for\n * `dataType`s are:\n *\n * - `'source'`: The non-tile data associated with any source\n * - `'style'`: The [style](https://maplibre.org/maplibre-style-spec/) used by the map\n *\n * Possible values for `sourceDataType`s are:\n *\n * - `'metadata'`: indicates that any necessary source metadata has been loaded (such as TileJSON) and it is ok to start loading tiles\n * - `'content'`: indicates the source data has changed (such as when source.setData() has been called on GeoJSONSource)\n * - `'visibility'`: send when the source becomes used when at least one of its layers becomes visible in style sense (inside the layer's zoom range and with layout.visibility set to 'visible')\n * - `'idle'`: indicates that no new source data has been fetched (but the source has done loading)\n *\n * @group Event Related\n *\n * @example\n * ```ts\n * // The sourcedata event is an example of MapDataEvent.\n * // Set up an event listener on the map.\n * map.on('sourcedata', (e) => {\n * if (e.isSourceLoaded) {\n * // Do something when the source has finished loading\n * }\n * });\n * ```\n */\nexport type MapDataEvent = {\n /**\n * The event type.\n */\n type: string;\n /**\n * The type of data that has changed. One of `'source'`, `'style'`.\n */\n dataType: string;\n /**\n * Included if the event has a `dataType` of `source` and the event signals that internal data has been received or changed. Possible values are `metadata`, `content`, `visibility` and `idle`.\n */\n sourceDataType: MapSourceDataType;\n};\n\n/**\n * The terrain event\n *\n * @group Event Related\n */\nexport type MapTerrainEvent = {\n type: 'terrain';\n};\n\n/**\n * An event related to the web gl context\n *\n * @group Event Related\n */\nexport type MapContextEvent = {\n type: 'webglcontextlost' | 'webglcontextrestored';\n originalEvent: WebGLContextEvent;\n};\n\n/**\n * The style image missing event\n *\n * @group Event Related\n *\n * @see [Generate and add a missing icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-missing-generated/)\n */\nexport type MapStyleImageMissingEvent = MapLibreEvent & {\n type: 'styleimagemissing';\n id: string;\n}\n","import {MapMouseEvent, MapTouchEvent, MapWheelEvent} from '../events';\nimport {Handler} from '../handler_manager';\nimport type {Map} from '../map';\nimport type Point from '@mapbox/point-geometry';\n\nexport class MapEventHandler implements Handler {\n\n _mousedownPos: Point;\n _clickTolerance: number;\n _map: Map;\n\n constructor(map: Map, options: {\n clickTolerance: number;\n }) {\n this._map = map;\n this._clickTolerance = options.clickTolerance;\n }\n\n reset() {\n delete this._mousedownPos;\n }\n\n wheel(e: WheelEvent) {\n // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n // - ScrollZoom\n return this._firePreventable(new MapWheelEvent(e.type, this._map, e));\n }\n\n mousedown(e: MouseEvent, point: Point) {\n this._mousedownPos = point;\n // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n // - MousePan\n // - MouseRotate\n // - MousePitch\n // - DblclickHandler\n return this._firePreventable(new MapMouseEvent(e.type, this._map, e));\n }\n\n mouseup(e: MouseEvent) {\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n click(e: MouseEvent, point: Point) {\n if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) return;\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n dblclick(e: MouseEvent) {\n // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n // - DblClickZoom\n return this._firePreventable(new MapMouseEvent(e.type, this._map, e));\n }\n\n mouseover(e: MouseEvent) {\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n mouseout(e: MouseEvent) {\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n touchstart(e: TouchEvent) {\n // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n // - TouchPan\n // - TouchZoom\n // - TouchRotate\n // - TouchPitch\n // - TapZoom\n // - SwipeZoom\n return this._firePreventable(new MapTouchEvent(e.type, this._map, e));\n }\n\n touchmove(e: TouchEvent) {\n this._map.fire(new MapTouchEvent(e.type, this._map, e));\n }\n\n touchend(e: TouchEvent) {\n this._map.fire(new MapTouchEvent(e.type, this._map, e));\n }\n\n touchcancel(e: TouchEvent) {\n this._map.fire(new MapTouchEvent(e.type, this._map, e));\n }\n\n _firePreventable(mapEvent: MapMouseEvent | MapTouchEvent | MapWheelEvent) {\n this._map.fire(mapEvent);\n if (mapEvent.defaultPrevented) {\n // returning an object marks the handler as active and resets other handlers\n return {};\n }\n }\n\n isEnabled() {\n return true;\n }\n\n isActive() {\n return false;\n }\n enable() {}\n disable() {}\n}\n\nexport class BlockableMapEventHandler {\n _map: Map;\n _delayContextMenu: boolean;\n _ignoreContextMenu: boolean;\n _contextMenuEvent: MouseEvent;\n\n constructor(map: Map) {\n this._map = map;\n }\n\n reset() {\n this._delayContextMenu = false;\n this._ignoreContextMenu = true;\n delete this._contextMenuEvent;\n }\n\n mousemove(e: MouseEvent) {\n // mousemove map events should not be fired when interaction handlers (pan, rotate, etc) are active\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n mousedown() {\n this._delayContextMenu = true;\n this._ignoreContextMenu = false;\n }\n\n mouseup() {\n this._delayContextMenu = false;\n if (this._contextMenuEvent) {\n this._map.fire(new MapMouseEvent('contextmenu', this._map, this._contextMenuEvent));\n delete this._contextMenuEvent;\n }\n }\n contextmenu(e: MouseEvent) {\n if (this._delayContextMenu) {\n // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake\n this._contextMenuEvent = e;\n } else if (!this._ignoreContextMenu) {\n // Windows: contextmenu fired on mouseup, so fire event now\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n // prevent browser context menu when necessary\n if (this._map.listens('contextmenu')) {\n e.preventDefault();\n }\n }\n\n isEnabled() {\n return true;\n }\n\n isActive() {\n return false;\n }\n enable() {}\n disable() {}\n}\n","import type {Map} from '../map';\nimport type {PointLike} from '../camera';\nimport type {Transform} from '../../geo/transform';\nimport Point from '@mapbox/point-geometry';\nimport {LngLat} from '../../geo/lng_lat';\n\n/**\n * @internal\n * Shared utilities for the Handler classes to access the correct camera state.\n * If Camera.transformCameraUpdate is specified or terrain is enabled, the\n * \"desired state\" of camera may differ from the state used for rendering. The\n * handlers need the \"desired state\" to track accumulated changes.\n */\nexport class TransformProvider {\n _map: Map;\n\n constructor(map: Map) {\n this._map = map;\n }\n\n get transform(): Transform {\n return this._map._requestedCameraState || this._map.transform;\n }\n\n get center() {\n return {lng: this.transform.center.lng, lat: this.transform.center.lat};\n }\n\n get zoom() {\n return this.transform.zoom;\n }\n\n get pitch() {\n return this.transform.pitch;\n }\n\n get bearing() {\n return this.transform.bearing;\n }\n\n unproject(point: PointLike): LngLat {\n return this.transform.pointLocation(Point.convert(point), this._map.terrain);\n }\n}\n","import {DOM} from '../../util/dom';\n\nimport {Event} from '../../util/evented';\nimport {TransformProvider} from './transform-provider';\n\nimport type {Map} from '../map';\nimport type Point from '@mapbox/point-geometry';\nimport {Handler} from '../handler_manager';\n\n/**\n * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box.\n * The bounding box is defined by clicking and holding `shift` while dragging the cursor.\n *\n * @group Handlers\n */\nexport class BoxZoomHandler implements Handler {\n _map: Map;\n _tr: TransformProvider;\n _el: HTMLElement;\n _container: HTMLElement;\n _enabled: boolean;\n _active: boolean;\n _startPos: Point;\n _lastPos: Point;\n _box: HTMLElement;\n _clickTolerance: number;\n\n /** @internal */\n constructor(map: Map, options: {\n clickTolerance: number;\n }) {\n this._map = map;\n this._tr = new TransformProvider(map);\n this._el = map.getCanvasContainer();\n this._container = map.getContainer();\n this._clickTolerance = options.clickTolerance || 1;\n }\n\n /**\n * Returns a Boolean indicating whether the \"box zoom\" interaction is enabled.\n *\n * @returns `true` if the \"box zoom\" interaction is enabled.\n */\n isEnabled() {\n return !!this._enabled;\n }\n\n /**\n * Returns a Boolean indicating whether the \"box zoom\" interaction is active, i.e. currently being used.\n *\n * @returns `true` if the \"box zoom\" interaction is active.\n */\n isActive() {\n return !!this._active;\n }\n\n /**\n * Enables the \"box zoom\" interaction.\n *\n * @example\n * ```ts\n * map.boxZoom.enable();\n * ```\n */\n enable() {\n if (this.isEnabled()) return;\n this._enabled = true;\n }\n\n /**\n * Disables the \"box zoom\" interaction.\n *\n * @example\n * ```ts\n * map.boxZoom.disable();\n * ```\n */\n disable() {\n if (!this.isEnabled()) return;\n this._enabled = false;\n }\n\n mousedown(e: MouseEvent, point: Point) {\n if (!this.isEnabled()) return;\n if (!(e.shiftKey && e.button === 0)) return;\n\n DOM.disableDrag();\n this._startPos = this._lastPos = point;\n this._active = true;\n }\n\n mousemoveWindow(e: MouseEvent, point: Point) {\n if (!this._active) return;\n\n const pos = point;\n\n if (this._lastPos.equals(pos) || (!this._box && pos.dist(this._startPos) < this._clickTolerance)) {\n return;\n }\n\n const p0 = this._startPos;\n this._lastPos = pos;\n\n if (!this._box) {\n this._box = DOM.create('div', 'maplibregl-boxzoom', this._container);\n this._container.classList.add('maplibregl-crosshair');\n this._fireEvent('boxzoomstart', e);\n }\n\n const minX = Math.min(p0.x, pos.x),\n maxX = Math.max(p0.x, pos.x),\n minY = Math.min(p0.y, pos.y),\n maxY = Math.max(p0.y, pos.y);\n\n DOM.setTransform(this._box, `translate(${minX}px,${minY}px)`);\n\n this._box.style.width = `${maxX - minX}px`;\n this._box.style.height = `${maxY - minY}px`;\n }\n\n mouseupWindow(e: MouseEvent, point: Point) {\n if (!this._active) return;\n\n if (e.button !== 0) return;\n\n const p0 = this._startPos,\n p1 = point;\n\n this.reset();\n\n DOM.suppressClick();\n\n if (p0.x === p1.x && p0.y === p1.y) {\n this._fireEvent('boxzoomcancel', e);\n } else {\n this._map.fire(new Event('boxzoomend', {originalEvent: e}));\n return {\n cameraAnimation: map => map.fitScreenCoordinates(p0, p1, this._tr.bearing, {linear: true})\n };\n }\n }\n\n keydown(e: KeyboardEvent) {\n if (!this._active) return;\n\n if (e.keyCode === 27) {\n this.reset();\n this._fireEvent('boxzoomcancel', e);\n }\n }\n\n reset() {\n this._active = false;\n\n this._container.classList.remove('maplibregl-crosshair');\n\n if (this._box) {\n DOM.remove(this._box);\n this._box = null;\n }\n\n DOM.enableDrag();\n\n delete this._startPos;\n delete this._lastPos;\n }\n\n _fireEvent(type: string, e: any) {\n return this._map.fire(new Event(type, {originalEvent: e}));\n }\n}\n","import Point from '@mapbox/point-geometry';\n\nexport function indexTouches(touches: Array, points: Array) {\n if (touches.length !== points.length) throw new Error(`The number of touches and points are not equal - touches ${touches.length}, points ${points.length}`);\n const obj = {};\n for (let i = 0; i < touches.length; i++) {\n obj[touches[i].identifier] = points[i];\n }\n return obj;\n}\n","import Point from '@mapbox/point-geometry';\nimport {indexTouches} from './handler_util';\n\nfunction getCentroid(points: Array) {\n const sum = new Point(0, 0);\n for (const point of points) {\n sum._add(point);\n }\n return sum.div(points.length);\n}\n\nexport const MAX_TAP_INTERVAL = 500;\nconst MAX_TOUCH_TIME = 500;\nexport const MAX_DIST = 30;\n\nexport class SingleTapRecognizer {\n\n numTouches: number;\n centroid: Point;\n startTime: number;\n aborted: boolean;\n touches: {\n [k in number | string]: Point;\n };\n\n constructor(options: {\n numTouches: number;\n }) {\n this.reset();\n this.numTouches = options.numTouches;\n }\n\n reset() {\n delete this.centroid;\n delete this.startTime;\n delete this.touches;\n this.aborted = false;\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n\n if (this.centroid || mapTouches.length > this.numTouches) {\n this.aborted = true;\n }\n if (this.aborted) {\n return;\n }\n\n if (this.startTime === undefined) {\n this.startTime = e.timeStamp;\n }\n\n if (mapTouches.length === this.numTouches) {\n this.centroid = getCentroid(points);\n this.touches = indexTouches(mapTouches, points);\n }\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n if (this.aborted || !this.centroid) return;\n\n const newTouches = indexTouches(mapTouches, points);\n for (const id in this.touches) {\n const prevPos = this.touches[id];\n const pos = newTouches[id];\n if (!pos || pos.dist(prevPos) > MAX_DIST) {\n this.aborted = true;\n }\n }\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) {\n this.aborted = true;\n }\n\n if (mapTouches.length === 0) {\n const centroid = !this.aborted && this.centroid;\n this.reset();\n if (centroid) return centroid;\n }\n }\n\n}\n\nexport class TapRecognizer {\n\n singleTap: SingleTapRecognizer;\n numTaps: number;\n lastTime: number;\n lastTap: Point;\n count: number;\n\n constructor(options: {\n numTaps: number;\n numTouches: number;\n }) {\n this.singleTap = new SingleTapRecognizer(options);\n this.numTaps = options.numTaps;\n this.reset();\n }\n\n reset() {\n this.lastTime = Infinity;\n delete this.lastTap;\n this.count = 0;\n this.singleTap.reset();\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n this.singleTap.touchstart(e, points, mapTouches);\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n this.singleTap.touchmove(e, points, mapTouches);\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n const tap = this.singleTap.touchend(e, points, mapTouches);\n if (tap) {\n const soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL;\n const closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST;\n\n if (!soonEnough || !closeEnough) {\n this.reset();\n }\n\n this.count++;\n this.lastTime = e.timeStamp;\n this.lastTap = tap;\n\n if (this.count === this.numTaps) {\n this.reset();\n return tap;\n }\n }\n }\n}\n","import {TapRecognizer} from './tap_recognizer';\nimport type Point from '@mapbox/point-geometry';\nimport type {Map} from '../map';\nimport {TransformProvider} from './transform-provider';\nimport {Handler} from '../handler_manager';\n\n/**\n * A `TapZoomHandler` allows the user to zoom the map at a point by double tapping\n */\nexport class TapZoomHandler implements Handler {\n _tr: TransformProvider;\n _enabled: boolean;\n _active: boolean;\n _zoomIn: TapRecognizer;\n _zoomOut: TapRecognizer;\n\n constructor(map: Map) {\n this._tr = new TransformProvider(map);\n this._zoomIn = new TapRecognizer({\n numTouches: 1,\n numTaps: 2\n });\n\n this._zoomOut = new TapRecognizer({\n numTouches: 2,\n numTaps: 1\n });\n\n this.reset();\n }\n\n reset() {\n this._active = false;\n this._zoomIn.reset();\n this._zoomOut.reset();\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n this._zoomIn.touchstart(e, points, mapTouches);\n this._zoomOut.touchstart(e, points, mapTouches);\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n this._zoomIn.touchmove(e, points, mapTouches);\n this._zoomOut.touchmove(e, points, mapTouches);\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches);\n const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches);\n const tr = this._tr;\n\n if (zoomInPoint) {\n this._active = true;\n e.preventDefault();\n setTimeout(() => this.reset(), 0);\n return {\n cameraAnimation: (map: Map) => map.easeTo({\n duration: 300,\n zoom: tr.zoom + 1,\n around: tr.unproject(zoomInPoint)\n }, {originalEvent: e})\n };\n } else if (zoomOutPoint) {\n this._active = true;\n e.preventDefault();\n setTimeout(() => this.reset(), 0);\n return {\n cameraAnimation: (map: Map) => map.easeTo({\n duration: 300,\n zoom: tr.zoom - 1,\n around: tr.unproject(zoomOutPoint)\n }, {originalEvent: e})\n };\n }\n }\n\n touchcancel() {\n this.reset();\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n","import {DOM} from '../../util/dom';\nimport type Point from '@mapbox/point-geometry';\nimport {DragMoveStateManager} from './drag_move_state_manager';\nimport {Handler} from '../handler_manager';\n\ninterface DragMovementResult {\n bearingDelta?: number;\n pitchDelta?: number;\n around?: Point;\n panDelta?: Point;\n}\n\nexport interface DragPanResult extends DragMovementResult {\n around: Point;\n panDelta: Point;\n}\n\nexport interface DragRotateResult extends DragMovementResult {\n bearingDelta: number;\n}\n\nexport interface DragPitchResult extends DragMovementResult {\n pitchDelta: number;\n}\n\ntype DragMoveFunction = (lastPoint: Point, point: Point) => T;\n\nexport interface DragMoveHandler extends Handler {\n dragStart: (e: E, point: Point) => void;\n dragMove: (e: E, point: Point) => T | void;\n dragEnd: (e: E) => void;\n getClickTolerance: () => number;\n}\n\nexport type DragMoveHandlerOptions = {\n /**\n * If the movement is shorter than this value, consider it a click.\n */\n clickTolerance: number;\n /**\n * The move function to run on a valid movement.\n */\n move: DragMoveFunction;\n /**\n * A class used to manage the state of the drag event - start, checking valid moves, end. See the class documentation for more details.\n */\n moveStateManager: DragMoveStateManager;\n /**\n * A method used to assign the dragStart, dragMove, and dragEnd methods to the relevant event handlers, as well as assigning the contextmenu handler\n * @param handler - the handler\n */\n assignEvents: (handler: DragMoveHandler) => void;\n /**\n * Should the move start on the \"start\" event, or should it start on the first valid move.\n */\n activateOnStart?: boolean;\n /**\n * If true, handler will be enabled during construction\n */\n enable?: boolean;\n}\n\n/**\n * A generic class to create handlers for drag events, from both mouse and touch events.\n */\nexport class DragHandler implements DragMoveHandler {\n // Event handlers that may be assigned by the implementations of this class\n contextmenu?: Handler['contextmenu'];\n mousedown?: Handler['mousedown'];\n mousemoveWindow?: Handler['mousemoveWindow'];\n mouseup?: Handler['mouseup'];\n touchstart?: Handler['touchstart'];\n touchmoveWindow?: Handler['touchmoveWindow'];\n touchend?: Handler['touchend'];\n\n _clickTolerance: number;\n _moveFunction: DragMoveFunction;\n _activateOnStart: boolean;\n _active: boolean;\n _enabled: boolean;\n _moved: boolean;\n _lastPoint: Point | null;\n _moveStateManager: DragMoveStateManager;\n\n constructor(options: DragMoveHandlerOptions) {\n this._enabled = !!options.enable;\n this._moveStateManager = options.moveStateManager;\n this._clickTolerance = options.clickTolerance || 1;\n this._moveFunction = options.move;\n this._activateOnStart = !!options.activateOnStart;\n\n options.assignEvents(this);\n\n this.reset();\n }\n\n reset(e?: E) {\n this._active = false;\n this._moved = false;\n delete this._lastPoint;\n this._moveStateManager.endMove(e);\n }\n\n _move(...params: Parameters>) {\n const move = this._moveFunction(...params);\n if (move.bearingDelta || move.pitchDelta || move.around || move.panDelta) {\n this._active = true;\n return move;\n }\n }\n\n dragStart(e: E, point: Point);\n dragStart(e: E, point: Point[]);\n dragStart(e: E, point: Point | Point[]) {\n if (!this.isEnabled() || this._lastPoint) return;\n\n if (!this._moveStateManager.isValidStartEvent(e)) return;\n this._moveStateManager.startMove(e);\n\n this._lastPoint = point['length'] ? point[0] : point;\n\n if (this._activateOnStart && this._lastPoint) this._active = true;\n }\n\n dragMove(e: E, point: Point);\n dragMove(e: E, point: Point[]);\n dragMove(e: E, point: Point | Point[]) {\n if (!this.isEnabled()) return;\n const lastPoint = this._lastPoint;\n if (!lastPoint) return;\n e.preventDefault();\n\n if (!this._moveStateManager.isValidMoveEvent(e)) {\n this.reset(e);\n return;\n }\n\n const movePoint = point['length'] ? point[0] : point;\n\n if (!this._moved && movePoint.dist(lastPoint) < this._clickTolerance) return;\n this._moved = true;\n this._lastPoint = movePoint;\n\n return this._move(lastPoint, movePoint);\n }\n\n dragEnd(e: E) {\n if (!this.isEnabled() || !this._lastPoint) return;\n if (!this._moveStateManager.isValidEndEvent(e)) return;\n if (this._moved) DOM.suppressClick();\n this.reset(e);\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n\n getClickTolerance() {\n return this._clickTolerance;\n }\n}\n","import {DOM} from '../../util/dom';\n\nconst LEFT_BUTTON = 0;\nconst RIGHT_BUTTON = 2;\n\n// the values for each button in MouseEvent.buttons\nconst BUTTONS_FLAGS = {\n [LEFT_BUTTON]: 1,\n [RIGHT_BUTTON]: 2\n};\n\nfunction buttonNoLongerPressed(e: MouseEvent, button: number) {\n const flag = BUTTONS_FLAGS[button];\n return e.buttons === undefined || (e.buttons & flag) !== flag;\n}\n\n/*\n * Drag events are initiated by specific interaction which needs to be tracked until it ends.\n * This requires some state management:\n * 1. registering the initiating event,\n * 2. tracking that it was not canceled / not confusing it with another event firing.\n * 3. recognizing the ending event and cleaning up any internal state\n *\n * Concretely, we implement two state managers:\n * 1. MouseMoveStateManager\n * Receives a functions that is used to recognize mouse events that should be registered as the\n * relevant drag interactions - i.e. dragging with the right mouse button, or while CTRL is pressed.\n * 2. OneFingerTouchMoveStateManager\n * Checks if a drag event is using one finger, and continuously tracking that this is the same event\n * (i.e. to make sure not additional finger has started interacting with the screen before raising\n * the first finger).\n */\nexport interface DragMoveStateManager {\n startMove: (e: E) => void;\n endMove: (e?: E) => void;\n isValidStartEvent: (e: E) => boolean;\n isValidMoveEvent: (e: E) => boolean;\n isValidEndEvent: (e?: E) => boolean;\n}\n\nexport class MouseMoveStateManager implements DragMoveStateManager {\n _eventButton: number | undefined;\n _correctEvent: (e: MouseEvent) => boolean;\n\n constructor(options: {\n checkCorrectEvent: (e: MouseEvent) => boolean;\n }) {\n this._correctEvent = options.checkCorrectEvent;\n }\n\n startMove(e: MouseEvent) {\n const eventButton = DOM.mouseButton(e);\n this._eventButton = eventButton;\n }\n\n endMove(_e?: MouseEvent) {\n delete this._eventButton;\n }\n\n isValidStartEvent(e: MouseEvent) {\n return this._correctEvent(e);\n }\n\n isValidMoveEvent(e: MouseEvent) {\n // Some browsers don't fire a `mouseup` when the mouseup occurs outside\n // the window or iframe:\n // https://github.com/mapbox/mapbox-gl-js/issues/4622\n //\n // If the button is no longer pressed during this `mousemove` it may have\n // been released outside of the window or iframe.\n return !buttonNoLongerPressed(e, this._eventButton);\n }\n\n isValidEndEvent(e: MouseEvent) {\n const eventButton = DOM.mouseButton(e);\n return eventButton === this._eventButton;\n }\n}\n\nexport class OneFingerTouchMoveStateManager implements DragMoveStateManager {\n _firstTouch: number | undefined;\n\n constructor() {\n this._firstTouch = undefined;\n }\n\n _isOneFingerTouch(e: TouchEvent) {\n return e.targetTouches.length === 1;\n }\n\n _isSameTouchEvent(e: TouchEvent) {\n return e.targetTouches[0].identifier === this._firstTouch;\n }\n\n startMove(e: TouchEvent) {\n const firstTouch = e.targetTouches[0].identifier;\n this._firstTouch = firstTouch;\n }\n\n endMove(_e?: TouchEvent) {\n delete this._firstTouch;\n }\n\n isValidStartEvent(e: TouchEvent) {\n return this._isOneFingerTouch(e);\n }\n\n isValidMoveEvent(e: TouchEvent) {\n return this._isOneFingerTouch(e) && this._isSameTouchEvent(e);\n }\n\n isValidEndEvent(e: TouchEvent) {\n return this._isOneFingerTouch(e) && this._isSameTouchEvent(e);\n }\n}\n","import type Point from '@mapbox/point-geometry';\n\nimport {DOM} from '../../util/dom';\nimport {DragMoveHandler, DragPanResult, DragRotateResult, DragPitchResult, DragHandler} from './drag_handler';\nimport {MouseMoveStateManager} from './drag_move_state_manager';\n\n/**\n * `MousePanHandler` allows the user to pan the map by clicking and dragging\n */\nexport interface MousePanHandler extends DragMoveHandler {}\n/**\n * `MouseRotateHandler` allows the user to rotate the map by clicking and dragging\n */\nexport interface MouseRotateHandler extends DragMoveHandler {}\n/**\n * `MousePitchHandler` allows the user to zoom the map by pitching\n */\nexport interface MousePitchHandler extends DragMoveHandler {}\n\nconst LEFT_BUTTON = 0;\nconst RIGHT_BUTTON = 2;\n\nconst assignEvents = (handler: DragHandler) => {\n handler.mousedown = handler.dragStart;\n handler.mousemoveWindow = handler.dragMove;\n handler.mouseup = handler.dragEnd;\n handler.contextmenu = (e: MouseEvent) => {\n e.preventDefault();\n };\n};\n\nexport const generateMousePanHandler = ({enable, clickTolerance,}: {\n clickTolerance: number;\n enable?: boolean;\n}): MousePanHandler => {\n const mouseMoveStateManager = new MouseMoveStateManager({\n checkCorrectEvent: (e: MouseEvent) => DOM.mouseButton(e) === LEFT_BUTTON && !e.ctrlKey,\n });\n return new DragHandler({\n clickTolerance,\n move: (lastPoint: Point, point: Point) =>\n ({around: point, panDelta: point.sub(lastPoint)}),\n activateOnStart: true,\n moveStateManager: mouseMoveStateManager,\n enable,\n assignEvents,\n });\n};\n\nexport const generateMouseRotationHandler = ({enable, clickTolerance, bearingDegreesPerPixelMoved = 0.8}: {\n clickTolerance: number;\n bearingDegreesPerPixelMoved?: number;\n enable?: boolean;\n}): MouseRotateHandler => {\n const mouseMoveStateManager = new MouseMoveStateManager({\n checkCorrectEvent: (e: MouseEvent): boolean =>\n (DOM.mouseButton(e) === LEFT_BUTTON && e.ctrlKey) ||\n (DOM.mouseButton(e) === RIGHT_BUTTON),\n });\n return new DragHandler({\n clickTolerance,\n move: (lastPoint: Point, point: Point) =>\n ({bearingDelta: (point.x - lastPoint.x) * bearingDegreesPerPixelMoved}),\n // prevent browser context menu when necessary; we don't allow it with rotation\n // because we can't discern rotation gesture start from contextmenu on Mac\n moveStateManager: mouseMoveStateManager,\n enable,\n assignEvents,\n });\n};\n\nexport const generateMousePitchHandler = ({enable, clickTolerance, pitchDegreesPerPixelMoved = -0.5}: {\n clickTolerance: number;\n pitchDegreesPerPixelMoved?: number;\n enable?: boolean;\n}): MousePitchHandler => {\n const mouseMoveStateManager = new MouseMoveStateManager({\n checkCorrectEvent: (e: MouseEvent): boolean =>\n (DOM.mouseButton(e) === LEFT_BUTTON && e.ctrlKey) ||\n (DOM.mouseButton(e) === RIGHT_BUTTON),\n });\n return new DragHandler({\n clickTolerance,\n move: (lastPoint: Point, point: Point) =>\n ({pitchDelta: (point.y - lastPoint.y) * pitchDegreesPerPixelMoved}),\n // prevent browser context menu when necessary; we don't allow it with rotation\n // because we can't discern rotation gesture start from contextmenu on Mac\n moveStateManager: mouseMoveStateManager,\n enable,\n assignEvents,\n });\n};\n","import Point from '@mapbox/point-geometry';\nimport {indexTouches} from './handler_util';\nimport {Handler} from '../handler_manager';\nimport type {Map} from '../map';\n\n/**\n * A `TouchPanHandler` allows the user to pan the map using touch gestures.\n */\nexport class TouchPanHandler implements Handler {\n\n _enabled: boolean;\n _active: boolean;\n _touches: {\n [k in string | number]: Point;\n };\n _clickTolerance: number;\n _sum: Point;\n _map: Map;\n\n constructor(options: {clickTolerance: number}, map: Map) {\n this._clickTolerance = options.clickTolerance || 1;\n this._map = map;\n this.reset();\n }\n\n reset() {\n this._active = false;\n this._touches = {};\n this._sum = new Point(0, 0);\n }\n\n _shouldBePrevented(touchesCount: number) {\n const minTouches = this._map.cooperativeGestures.isEnabled() ? 2 : 1;\n return touchesCount < minTouches;\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n return this._calculateTransform(e, points, mapTouches);\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this._active) return;\n if (this._shouldBePrevented(mapTouches.length)) {\n this._map.cooperativeGestures.notifyGestureBlocked('touch_pan', e);\n return;\n }\n e.preventDefault();\n return this._calculateTransform(e, points, mapTouches);\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n this._calculateTransform(e, points, mapTouches);\n\n if (this._active && this._shouldBePrevented(mapTouches.length)) {\n this.reset();\n }\n }\n\n touchcancel() {\n this.reset();\n }\n\n _calculateTransform(e: TouchEvent, points: Array, mapTouches: Array) {\n if (mapTouches.length > 0) this._active = true;\n\n const touches = indexTouches(mapTouches, points);\n\n const touchPointSum = new Point(0, 0);\n const touchDeltaSum = new Point(0, 0);\n let touchDeltaCount = 0;\n\n for (const identifier in touches) {\n const point = touches[identifier];\n const prevPoint = this._touches[identifier];\n if (prevPoint) {\n touchPointSum._add(point);\n touchDeltaSum._add(point.sub(prevPoint));\n touchDeltaCount++;\n touches[identifier] = point;\n }\n }\n\n this._touches = touches;\n\n if (this._shouldBePrevented(touchDeltaCount) || !touchDeltaSum.mag()) return;\n\n const panDelta = touchDeltaSum.div(touchDeltaCount);\n this._sum._add(panDelta);\n if (this._sum.mag() < this._clickTolerance) return;\n\n const around = touchPointSum.div(touchDeltaCount);\n\n return {\n around,\n panDelta\n };\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n","import Point from '@mapbox/point-geometry';\nimport {DOM} from '../../util/dom';\nimport type {Map} from '../map';\nimport {Handler, HandlerResult} from '../handler_manager';\n\n/**\n * An options object sent to the enable function of some of the handlers\n */\nexport type AroundCenterOptions = {\n /**\n * If \"center\" is passed, map will zoom around the center of map\n */\n around: 'center';\n}\n\n/**\n * The `TwoFingersTouchHandler`s allows the user to zoom, pitch and rotate the map using two fingers\n *\n */\nabstract class TwoFingersTouchHandler implements Handler {\n\n _enabled?: boolean;\n _active?: boolean;\n _firstTwoTouches?: [number, number];\n _vector?: Point;\n _startVector?: Point;\n _aroundCenter?: boolean;\n\n /** @internal */\n constructor() {\n this.reset();\n }\n\n reset(): void {\n this._active = false;\n delete this._firstTwoTouches;\n }\n\n abstract _start(points: [Point, Point]): void;\n abstract _move(points: [Point, Point], pinchAround: Point | null, e: TouchEvent): HandlerResult | void;\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array): void {\n //log('touchstart', points, e.target.innerHTML, e.targetTouches.length ? e.targetTouches[0].target.innerHTML: undefined);\n if (this._firstTwoTouches || mapTouches.length < 2) return;\n\n this._firstTwoTouches = [\n mapTouches[0].identifier,\n mapTouches[1].identifier\n ];\n\n // implemented by child classes\n this._start([points[0], points[1]]);\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array): HandlerResult | void {\n if (!this._firstTwoTouches) return;\n\n e.preventDefault();\n\n const [idA, idB] = this._firstTwoTouches;\n const a = getTouchById(mapTouches, points, idA);\n const b = getTouchById(mapTouches, points, idB);\n if (!a || !b) return;\n const pinchAround = this._aroundCenter ? null : a.add(b).div(2);\n\n // implemented by child classes\n return this._move([a, b], pinchAround, e);\n\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array): void {\n if (!this._firstTwoTouches) return;\n\n const [idA, idB] = this._firstTwoTouches;\n const a = getTouchById(mapTouches, points, idA);\n const b = getTouchById(mapTouches, points, idB);\n if (a && b) return;\n\n if (this._active) DOM.suppressClick();\n\n this.reset();\n }\n\n touchcancel(): void {\n this.reset();\n }\n\n /**\n * Enables the \"drag to pitch\" interaction.\n *\n * @example\n * ```ts\n * map.touchPitch.enable();\n * ```\n */\n enable(options?: AroundCenterOptions | boolean | null): void {\n this._enabled = true;\n this._aroundCenter = !!options && (options as AroundCenterOptions).around === 'center';\n }\n\n /**\n * Disables the \"drag to pitch\" interaction.\n *\n * @example\n * ```ts\n * map.touchPitch.disable();\n * ```\n */\n disable(): void {\n this._enabled = false;\n this.reset();\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to pitch\" interaction is enabled.\n *\n * @returns `true` if the \"drag to pitch\" interaction is enabled.\n */\n isEnabled(): boolean {\n return !!this._enabled;\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to pitch\" interaction is active, i.e. currently being used.\n *\n * @returns `true` if the \"drag to pitch\" interaction is active.\n */\n isActive(): boolean {\n return !!this._active;\n }\n}\n\nfunction getTouchById(mapTouches: Array, points: Array, identifier: number): Point | undefined {\n for (let i = 0; i < mapTouches.length; i++) {\n if (mapTouches[i].identifier === identifier) return points[i];\n }\n return undefined;\n}\n\n/* ZOOM */\n\nconst ZOOM_THRESHOLD = 0.1;\n\nfunction getZoomDelta(distance: number, lastDistance: number): number {\n return Math.log(distance / lastDistance) / Math.LN2;\n}\n\n/**\n * The `TwoFingersTouchHandler`s allows the user to zoom the map two fingers\n *\n * @group Handlers\n */\nexport class TwoFingersTouchZoomHandler extends TwoFingersTouchHandler {\n\n _distance?: number;\n _startDistance?: number;\n\n reset() {\n super.reset();\n delete this._distance;\n delete this._startDistance;\n }\n\n _start(points: [Point, Point]): void {\n this._startDistance = this._distance = points[0].dist(points[1]);\n }\n\n _move(points: [Point, Point], pinchAround: Point | null): HandlerResult | void {\n const lastDistance = this._distance!;\n this._distance = points[0].dist(points[1]);\n if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance!)) < ZOOM_THRESHOLD) return;\n this._active = true;\n return {\n zoomDelta: getZoomDelta(this._distance, lastDistance),\n pinchAround\n };\n }\n}\n\n/* ROTATE */\n\nconst ROTATION_THRESHOLD = 25; // pixels along circumference of touch circle\n\nfunction getBearingDelta(a: Point, b: Point): number {\n return a.angleWith(b) * 180 / Math.PI;\n}\n\n/**\n * The `TwoFingersTouchHandler`s allows the user to rotate the map two fingers\n *\n * @group Handlers\n */\nexport class TwoFingersTouchRotateHandler extends TwoFingersTouchHandler {\n _minDiameter?: number;\n\n reset(): void {\n super.reset();\n delete this._minDiameter;\n delete this._startVector;\n delete this._vector;\n }\n\n _start(points: [Point, Point]): void {\n this._startVector = this._vector = points[0].sub(points[1]);\n this._minDiameter = points[0].dist(points[1]);\n }\n\n _move(points: [Point, Point], pinchAround: Point | null, _e: TouchEvent): HandlerResult | void {\n const lastVector = this._vector!;\n this._vector = points[0].sub(points[1]);\n\n if (!this._active && this._isBelowThreshold(this._vector)) return;\n this._active = true;\n\n return {\n bearingDelta: getBearingDelta(this._vector, lastVector),\n pinchAround\n };\n }\n\n _isBelowThreshold(vector: Point): boolean {\n /*\n * The threshold before a rotation actually happens is configured in\n * pixels along the circumference of the circle formed by the two fingers.\n * This makes the threshold in degrees larger when the fingers are close\n * together and smaller when the fingers are far apart.\n *\n * Use the smallest diameter from the whole gesture to reduce sensitivity\n * when pinching in and out.\n */\n\n this._minDiameter = Math.min(this._minDiameter!, vector.mag());\n const circumference = Math.PI * this._minDiameter;\n const threshold = ROTATION_THRESHOLD / circumference * 360;\n\n const bearingDeltaSinceStart = getBearingDelta(vector, this._startVector!);\n return Math.abs(bearingDeltaSinceStart) < threshold;\n }\n}\n\n/* PITCH */\n\nfunction isVertical(vector: Point): boolean {\n return Math.abs(vector.y) > Math.abs(vector.x);\n}\n\nconst ALLOWED_SINGLE_TOUCH_TIME = 100;\n\n/**\n * The `TwoFingersTouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers.\n *\n * @group Handlers\n */\nexport class TwoFingersTouchPitchHandler extends TwoFingersTouchHandler {\n\n _valid?: boolean;\n _firstMove?: number;\n _lastPoints?: [Point, Point];\n _map: Map;\n _currentTouchCount: number = 0;\n\n constructor(map: Map) {\n super();\n this._map = map;\n }\n\n reset(): void {\n super.reset();\n this._valid = undefined;\n delete this._firstMove;\n delete this._lastPoints;\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array): void {\n super.touchstart(e, points, mapTouches);\n this._currentTouchCount = mapTouches.length;\n }\n\n _start(points: [Point, Point]): void {\n this._lastPoints = points;\n if (isVertical(points[0].sub(points[1]))) {\n // fingers are more horizontal than vertical\n this._valid = false;\n }\n }\n\n _move(points: [Point, Point], center: Point | null, e: TouchEvent): HandlerResult | void {\n // If cooperative gestures is enabled, we need a 3-finger minimum for this gesture to register\n if (this._map.cooperativeGestures.isEnabled() && this._currentTouchCount < 3) {\n return;\n }\n\n const vectorA = points[0].sub(this._lastPoints![0]);\n const vectorB = points[1].sub(this._lastPoints![1]);\n\n this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp);\n if (!this._valid) return;\n\n this._lastPoints = points;\n this._active = true;\n const yDeltaAverage = (vectorA.y + vectorB.y) / 2;\n const degreesPerPixelMoved = -0.5;\n return {\n pitchDelta: yDeltaAverage * degreesPerPixelMoved\n };\n }\n\n gestureBeginsVertically(vectorA: Point, vectorB: Point, timeStamp: number): boolean | undefined {\n if (this._valid !== undefined) return this._valid;\n\n const threshold = 2;\n const movedA = vectorA.mag() >= threshold;\n const movedB = vectorB.mag() >= threshold;\n\n // neither finger has moved a meaningful amount, wait\n if (!movedA && !movedB) return;\n\n // One finger has moved and the other has not.\n // If enough time has passed, decide it is not a pitch.\n if (!movedA || !movedB) {\n if (this._firstMove === undefined) {\n this._firstMove = timeStamp;\n }\n\n if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) {\n // still waiting for a movement from the second finger\n return undefined;\n } else {\n return false;\n }\n }\n\n const isSameDirection = vectorA.y > 0 === vectorB.y > 0;\n return isVertical(vectorA) && isVertical(vectorB) && isSameDirection;\n }\n}\n","import {Handler} from '../handler_manager';\nimport type {Map} from '../map';\nimport {TransformProvider} from './transform-provider';\n\nconst defaultOptions = {\n panStep: 100,\n bearingStep: 15,\n pitchStep: 10\n};\n\n/**\n * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using\n * the following keyboard shortcuts:\n *\n * - `=` / `+`: Increase the zoom level by 1.\n * - `Shift-=` / `Shift-+`: Increase the zoom level by 2.\n * - `-`: Decrease the zoom level by 1.\n * - `Shift--`: Decrease the zoom level by 2.\n * - Arrow keys: Pan by 100 pixels.\n * - `Shift+⇢`: Increase the rotation by 15 degrees.\n * - `Shift+⇠`: Decrease the rotation by 15 degrees.\n * - `Shift+⇡`: Increase the pitch by 10 degrees.\n * - `Shift+⇣`: Decrease the pitch by 10 degrees.\n *\n * @group Handlers\n */\nexport class KeyboardHandler implements Handler {\n _tr: TransformProvider;\n _enabled: boolean;\n _active: boolean;\n _panStep: number;\n _bearingStep: number;\n _pitchStep: number;\n _rotationDisabled: boolean;\n\n /** @internal */\n constructor(map: Map) {\n this._tr = new TransformProvider(map);\n const stepOptions = defaultOptions;\n this._panStep = stepOptions.panStep;\n this._bearingStep = stepOptions.bearingStep;\n this._pitchStep = stepOptions.pitchStep;\n this._rotationDisabled = false;\n }\n\n reset() {\n this._active = false;\n }\n\n keydown(e: KeyboardEvent) {\n if (e.altKey || e.ctrlKey || e.metaKey) return;\n\n let zoomDir = 0;\n let bearingDir = 0;\n let pitchDir = 0;\n let xDir = 0;\n let yDir = 0;\n\n switch (e.keyCode) {\n case 61:\n case 107:\n case 171:\n case 187:\n zoomDir = 1;\n break;\n\n case 189:\n case 109:\n case 173:\n zoomDir = -1;\n break;\n\n case 37:\n if (e.shiftKey) {\n bearingDir = -1;\n } else {\n e.preventDefault();\n xDir = -1;\n }\n break;\n\n case 39:\n if (e.shiftKey) {\n bearingDir = 1;\n } else {\n e.preventDefault();\n xDir = 1;\n }\n break;\n\n case 38:\n if (e.shiftKey) {\n pitchDir = 1;\n } else {\n e.preventDefault();\n yDir = -1;\n }\n break;\n\n case 40:\n if (e.shiftKey) {\n pitchDir = -1;\n } else {\n e.preventDefault();\n yDir = 1;\n }\n break;\n\n default:\n return;\n }\n\n if (this._rotationDisabled) {\n bearingDir = 0;\n pitchDir = 0;\n }\n\n return {\n cameraAnimation: (map: Map) => {\n const tr = this._tr;\n map.easeTo({\n duration: 300,\n easeId: 'keyboardHandler',\n easing: easeOut,\n\n zoom: zoomDir ? Math.round(tr.zoom) + zoomDir * (e.shiftKey ? 2 : 1) : tr.zoom,\n bearing: tr.bearing + bearingDir * this._bearingStep,\n pitch: tr.pitch + pitchDir * this._pitchStep,\n offset: [-xDir * this._panStep, -yDir * this._panStep],\n center: tr.center\n }, {originalEvent: e});\n }\n };\n }\n\n /**\n * Enables the \"keyboard rotate and zoom\" interaction.\n *\n * @example\n * ```ts\n * map.keyboard.enable();\n * ```\n */\n enable() {\n this._enabled = true;\n }\n\n /**\n * Disables the \"keyboard rotate and zoom\" interaction.\n *\n * @example\n * ```ts\n * map.keyboard.disable();\n * ```\n */\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n /**\n * Returns a Boolean indicating whether the \"keyboard rotate and zoom\"\n * interaction is enabled.\n *\n * @returns `true` if the \"keyboard rotate and zoom\"\n * interaction is enabled.\n */\n isEnabled() {\n return this._enabled;\n }\n\n /**\n * Returns true if the handler is enabled and has detected the start of a\n * zoom/rotate gesture.\n *\n * @returns `true` if the handler is enabled and has detected the\n * start of a zoom/rotate gesture.\n */\n isActive() {\n return this._active;\n }\n\n /**\n * Disables the \"keyboard pan/rotate\" interaction, leaving the\n * \"keyboard zoom\" interaction enabled.\n *\n * @example\n * ```ts\n * map.keyboard.disableRotation();\n * ```\n */\n disableRotation() {\n this._rotationDisabled = true;\n }\n\n /**\n * Enables the \"keyboard pan/rotate\" interaction.\n *\n * @example\n * ```ts\n * map.keyboard.enable();\n * map.keyboard.enableRotation();\n * ```\n */\n enableRotation() {\n this._rotationDisabled = false;\n }\n}\n\nfunction easeOut(t: number) {\n return t * (2 - t);\n}\n","import {DOM} from '../../util/dom';\n\nimport {defaultEasing, bezier} from '../../util/util';\nimport {browser} from '../../util/browser';\nimport {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {LngLat} from '../../geo/lng_lat';\nimport {TransformProvider} from './transform-provider';\n\nimport type {Map} from '../map';\nimport type Point from '@mapbox/point-geometry';\nimport type {AroundCenterOptions} from './two_fingers_touch';\nimport {Handler} from '../handler_manager';\n\n// deltaY value for mouse scroll wheel identification\nconst wheelZoomDelta = 4.000244140625;\n\n// These magic numbers control the rate of zoom. Trackpad events fire at a greater\n// frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick\nconst defaultZoomRate = 1 / 100;\nconst wheelZoomRate = 1 / 450;\n\n// upper bound on how much we scale the map in any single render frame; this\n// is used to limit zoom rate in the case of very fast scrolling\nconst maxScalePerFrame = 2;\n\n/**\n * The `ScrollZoomHandler` allows the user to zoom the map by scrolling.\n *\n * @group Handlers\n */\nexport class ScrollZoomHandler implements Handler {\n _map: Map;\n _tr: TransformProvider;\n _enabled: boolean;\n _active: boolean;\n _zooming: boolean;\n _aroundCenter: boolean;\n _around: LngLat;\n _aroundPoint: Point;\n _type: 'wheel' | 'trackpad' | null;\n _lastValue: number;\n _timeout: ReturnType; // used for delayed-handling of a single wheel movement\n _finishTimeout: ReturnType; // used to delay final '{move,zoom}end' events\n\n _lastWheelEvent: any;\n _lastWheelEventTime: number;\n\n _startZoom: number;\n _targetZoom: number;\n _delta: number;\n _easing: ((a: number) => number);\n _prevEase: {\n start: number;\n duration: number;\n easing: (_: number) => number;\n };\n\n _frameId: boolean;\n _triggerRenderFrame: () => void;\n\n _defaultZoomRate: number;\n _wheelZoomRate: number;\n\n /** @internal */\n constructor(map: Map, triggerRenderFrame: () => void) {\n this._map = map;\n this._tr = new TransformProvider(map);\n this._triggerRenderFrame = triggerRenderFrame;\n\n this._delta = 0;\n\n this._defaultZoomRate = defaultZoomRate;\n this._wheelZoomRate = wheelZoomRate;\n }\n\n /**\n * Set the zoom rate of a trackpad\n * @param zoomRate - 1/100 The rate used to scale trackpad movement to a zoom value.\n * @example\n * Speed up trackpad zoom\n * ```ts\n * map.scrollZoom.setZoomRate(1/25);\n * ```\n */\n setZoomRate(zoomRate: number) {\n this._defaultZoomRate = zoomRate;\n }\n\n /**\n * Set the zoom rate of a mouse wheel\n * @param wheelZoomRate - 1/450 The rate used to scale mouse wheel movement to a zoom value.\n * @example\n * Slow down zoom of mouse wheel\n * ```ts\n * map.scrollZoom.setWheelZoomRate(1/600);\n * ```\n */\n setWheelZoomRate(wheelZoomRate: number) {\n this._wheelZoomRate = wheelZoomRate;\n }\n\n /**\n * Returns a Boolean indicating whether the \"scroll to zoom\" interaction is enabled.\n * @returns `true` if the \"scroll to zoom\" interaction is enabled.\n */\n isEnabled() {\n return !!this._enabled;\n }\n\n /*\n * Active state is turned on and off with every scroll wheel event and is set back to false before the map\n * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in\n * progress.\n */\n isActive() {\n return !!this._active || this._finishTimeout !== undefined;\n }\n\n isZooming() {\n return !!this._zooming;\n }\n\n /**\n * Enables the \"scroll to zoom\" interaction.\n *\n * @param options - Options object.\n * @example\n * ```ts\n * map.scrollZoom.enable();\n * map.scrollZoom.enable({ around: 'center' })\n * ```\n */\n enable(options?: AroundCenterOptions | boolean) {\n if (this.isEnabled()) return;\n this._enabled = true;\n this._aroundCenter = !!options && (options as AroundCenterOptions).around === 'center';\n }\n\n /**\n * Disables the \"scroll to zoom\" interaction.\n *\n * @example\n * ```ts\n * map.scrollZoom.disable();\n * ```\n */\n disable() {\n if (!this.isEnabled()) return;\n this._enabled = false;\n }\n\n /**\n * Determines whether or not the gesture is blocked due to cooperativeGestures.\n */\n _shouldBePrevented(e: WheelEvent) {\n if (!this._map.cooperativeGestures.isEnabled()) {\n return false;\n }\n\n const isTrackpadPinch = e.ctrlKey;\n const isBypassed = isTrackpadPinch || this._map.cooperativeGestures.isBypassed(e);\n\n return !isBypassed;\n }\n\n wheel(e: WheelEvent) {\n if (!this.isEnabled()) return;\n if (this._shouldBePrevented(e)) {\n this._map.cooperativeGestures.notifyGestureBlocked('wheel_zoom', e);\n return;\n }\n let value = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY;\n const now = browser.now(),\n timeDelta = now - (this._lastWheelEventTime || 0);\n\n this._lastWheelEventTime = now;\n\n if (value !== 0 && (value % wheelZoomDelta) === 0) {\n // This one is definitely a mouse wheel event.\n this._type = 'wheel';\n\n } else if (value !== 0 && Math.abs(value) < 4) {\n // This one is definitely a trackpad event because it is so small.\n this._type = 'trackpad';\n\n } else if (timeDelta > 400) {\n // This is likely a new scroll action.\n this._type = null;\n this._lastValue = value;\n\n // Start a timeout in case this was a singular event, and delay it by up to 40ms.\n this._timeout = setTimeout(this._onTimeout, 40, e);\n\n } else if (!this._type) {\n // This is a repeating event, but we don't know the type of event just yet.\n // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode.\n this._type = (Math.abs(timeDelta * value) < 200) ? 'trackpad' : 'wheel';\n\n // Make sure our delayed event isn't fired again, because we accumulate\n // the previous event (which was less than 40ms ago) into this event.\n if (this._timeout) {\n clearTimeout(this._timeout);\n this._timeout = null;\n value += this._lastValue;\n }\n }\n\n // Slow down zoom if shift key is held for more precise zooming\n if (e.shiftKey && value) value = value / 4;\n\n // Only fire the callback if we actually know what type of scrolling device the user uses.\n if (this._type) {\n this._lastWheelEvent = e;\n this._delta -= value;\n if (!this._active) {\n this._start(e);\n }\n }\n\n e.preventDefault();\n }\n\n _onTimeout = (initialEvent: MouseEvent) => {\n this._type = 'wheel';\n this._delta -= this._lastValue;\n if (!this._active) {\n this._start(initialEvent);\n }\n };\n\n _start(e: MouseEvent) {\n if (!this._delta) return;\n\n if (this._frameId) {\n this._frameId = null;\n }\n\n this._active = true;\n if (!this.isZooming()) {\n this._zooming = true;\n }\n\n if (this._finishTimeout) {\n clearTimeout(this._finishTimeout);\n delete this._finishTimeout;\n }\n\n const pos = DOM.mousePos(this._map.getCanvas(), e);\n const tr = this._tr;\n\n if (pos.y > tr.transform.height / 2 - tr.transform.getHorizon()) {\n this._around = LngLat.convert(this._aroundCenter ? tr.center : tr.unproject(pos));\n } else {\n // Do not use current cursor position if above the horizon to avoid 'unproject' this point\n // as it is not mapped into 'coords' framebuffer or inversible with 'pixelMatrixInverse'.\n this._around = LngLat.convert(tr.center);\n }\n\n this._aroundPoint = tr.transform.locationPoint(this._around);\n if (!this._frameId) {\n this._frameId = true;\n this._triggerRenderFrame();\n }\n }\n\n renderFrame() {\n if (!this._frameId) return;\n this._frameId = null;\n\n if (!this.isActive()) return;\n const tr = this._tr.transform;\n\n // if we've had scroll events since the last render frame, consume the\n // accumulated delta, and update the target zoom level accordingly\n if (this._delta !== 0) {\n // For trackpad events and single mouse wheel ticks, use the default zoom rate\n const zoomRate = (this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta) ? this._wheelZoomRate : this._defaultZoomRate;\n // Scale by sigmoid of scroll wheel delta.\n let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate)));\n\n if (this._delta < 0 && scale !== 0) {\n scale = 1 / scale;\n }\n\n const fromScale = typeof this._targetZoom === 'number' ? tr.zoomScale(this._targetZoom) : tr.scale;\n this._targetZoom = Math.min(tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale)));\n\n // if this is a mouse wheel, refresh the starting zoom and easing\n // function we're using to smooth out the zooming between wheel\n // events\n if (this._type === 'wheel') {\n this._startZoom = tr.zoom;\n this._easing = this._smoothOutEasing(200);\n }\n\n this._delta = 0;\n }\n\n const targetZoom = typeof this._targetZoom === 'number' ?\n this._targetZoom : tr.zoom;\n const startZoom = this._startZoom;\n const easing = this._easing;\n\n let finished = false;\n let zoom;\n\n const lastWheelEventTimeDiff = browser.now() - this._lastWheelEventTime;\n if (this._type === 'wheel' && startZoom && easing && lastWheelEventTimeDiff) {\n const t = Math.min(lastWheelEventTimeDiff / 200, 1);\n\n const k = easing(t);\n zoom = interpolates.number(startZoom, targetZoom, k);\n if (t < 1) {\n if (!this._frameId) {\n this._frameId = true;\n }\n } else {\n finished = true;\n }\n } else {\n zoom = targetZoom;\n finished = true;\n }\n\n this._active = true;\n\n if (finished) {\n this._active = false;\n this._finishTimeout = setTimeout(() => {\n this._zooming = false;\n this._triggerRenderFrame();\n delete this._targetZoom;\n delete this._finishTimeout;\n }, 200);\n }\n\n return {\n noInertia: true,\n needsRenderFrame: !finished,\n zoomDelta: zoom - tr.zoom,\n around: this._aroundPoint,\n originalEvent: this._lastWheelEvent\n };\n }\n\n _smoothOutEasing(duration: number) {\n let easing = defaultEasing;\n\n if (this._prevEase) {\n const currentEase = this._prevEase;\n const t = (browser.now() - currentEase.start) / currentEase.duration;\n const speed = currentEase.easing(t + 0.01) - currentEase.easing(t);\n\n // Quick hack to make new bezier that is continuous with last\n const x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01;\n const y = Math.sqrt(0.27 * 0.27 - x * x);\n\n easing = bezier(x, y, 0.25, 1);\n }\n\n this._prevEase = {\n start: browser.now(),\n duration,\n easing\n };\n\n return easing;\n }\n\n reset() {\n this._active = false;\n this._zooming = false;\n delete this._targetZoom;\n if (this._finishTimeout) {\n clearTimeout(this._finishTimeout);\n delete this._finishTimeout;\n }\n }\n}\n","import type {ClickZoomHandler} from '../click_zoom';\nimport type {TapZoomHandler} from './../tap_zoom';\n\n/**\n * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by\n * double clicking or double tapping.\n *\n * @group Handlers\n */\nexport class DoubleClickZoomHandler {\n\n _clickZoom: ClickZoomHandler;\n _tapZoom: TapZoomHandler;\n\n /** @internal */\n constructor(clickZoom: ClickZoomHandler, TapZoom: TapZoomHandler) {\n this._clickZoom = clickZoom;\n this._tapZoom = TapZoom;\n }\n\n /**\n * Enables the \"double click to zoom\" interaction.\n *\n * @example\n * ```ts\n * map.doubleClickZoom.enable();\n * ```\n */\n enable() {\n this._clickZoom.enable();\n this._tapZoom.enable();\n }\n\n /**\n * Disables the \"double click to zoom\" interaction.\n *\n * @example\n * ```ts\n * map.doubleClickZoom.disable();\n * ```\n */\n disable() {\n this._clickZoom.disable();\n this._tapZoom.disable();\n }\n\n /**\n * Returns a Boolean indicating whether the \"double click to zoom\" interaction is enabled.\n *\n * @returns `true` if the \"double click to zoom\" interaction is enabled.\n */\n isEnabled() {\n return this._clickZoom.isEnabled() && this._tapZoom.isEnabled();\n }\n\n /**\n * Returns a Boolean indicating whether the \"double click to zoom\" interaction is active, i.e. currently being used.\n *\n * @returns `true` if the \"double click to zoom\" interaction is active.\n */\n isActive() {\n return this._clickZoom.isActive() || this._tapZoom.isActive();\n }\n}\n","import type Point from '@mapbox/point-geometry';\nimport type {Map} from '../map';\nimport {TransformProvider} from './transform-provider';\nimport {Handler} from '../handler_manager';\n\n/**\n * The `ClickZoomHandler` allows the user to zoom the map at a point by double clicking\n * It is used by other handlers\n */\nexport class ClickZoomHandler implements Handler {\n\n _tr: TransformProvider;\n _enabled: boolean;\n _active: boolean;\n\n /** @internal */\n constructor(map: Map) {\n this._tr = new TransformProvider(map);\n this.reset();\n }\n\n reset() {\n this._active = false;\n }\n\n dblclick(e: MouseEvent, point: Point) {\n e.preventDefault();\n return {\n cameraAnimation: (map: Map) => {\n map.easeTo({\n duration: 300,\n zoom: this._tr.zoom + (e.shiftKey ? -1 : 1),\n around: this._tr.unproject(point)\n }, {originalEvent: e});\n }\n };\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n","import {Handler} from '../handler_manager';\nimport {TapRecognizer, MAX_TAP_INTERVAL, MAX_DIST} from './tap_recognizer';\nimport type Point from '@mapbox/point-geometry';\n\n/**\n * A `TapDragZoomHandler` allows the user to zoom the map at a point by double tapping. It also allows the user pan the map by dragging.\n */\nexport class TapDragZoomHandler implements Handler {\n\n _enabled: boolean;\n _active: boolean;\n _swipePoint: Point;\n _swipeTouch: number;\n _tapTime: number;\n _tapPoint: Point;\n _tap: TapRecognizer;\n\n constructor() {\n\n this._tap = new TapRecognizer({\n numTouches: 1,\n numTaps: 1\n });\n\n this.reset();\n }\n\n reset() {\n this._active = false;\n delete this._swipePoint;\n delete this._swipeTouch;\n delete this._tapTime;\n delete this._tapPoint;\n this._tap.reset();\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n if (this._swipePoint) return;\n\n if (!this._tapTime) {\n this._tap.touchstart(e, points, mapTouches);\n } else {\n const swipePoint = points[0];\n\n const soonEnough = e.timeStamp - this._tapTime < MAX_TAP_INTERVAL;\n const closeEnough = this._tapPoint.dist(swipePoint) < MAX_DIST;\n\n if (!soonEnough || !closeEnough) {\n this.reset();\n } else if (mapTouches.length > 0) {\n this._swipePoint = swipePoint;\n this._swipeTouch = mapTouches[0].identifier;\n }\n }\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this._tapTime) {\n this._tap.touchmove(e, points, mapTouches);\n } else if (this._swipePoint) {\n if (mapTouches[0].identifier !== this._swipeTouch) {\n return;\n }\n\n const newSwipePoint = points[0];\n const dist = newSwipePoint.y - this._swipePoint.y;\n this._swipePoint = newSwipePoint;\n\n e.preventDefault();\n this._active = true;\n\n return {\n zoomDelta: dist / 128\n };\n }\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this._tapTime) {\n const point = this._tap.touchend(e, points, mapTouches);\n if (point) {\n this._tapTime = e.timeStamp;\n this._tapPoint = point;\n }\n } else if (this._swipePoint) {\n if (mapTouches.length === 0) {\n this.reset();\n }\n }\n }\n\n touchcancel() {\n this.reset();\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n","import type {MousePanHandler} from '../mouse';\nimport type {TouchPanHandler} from './../touch_pan';\n\n/**\n * A {@link DragPanHandler} options object\n */\nexport type DragPanOptions = {\n /**\n * factor used to scale the drag velocity\n * @defaultValue 0\n */\n linearity?: number;\n /**\n * easing function applied to `map.panTo` when applying the drag.\n * @param t - the easing function\n * @defaultValue bezier(0, 0, 0.3, 1)\n */\n easing?: (t: number) => number;\n /**\n * the maximum value of the drag velocity.\n * @defaultValue 1400\n */\n deceleration?: number;\n /**\n * the rate at which the speed reduces after the pan ends.\n * @defaultValue 2500\n */\n maxSpeed?: number;\n};\n\n/**\n * The `DragPanHandler` allows the user to pan the map by clicking and dragging\n * the cursor.\n *\n * @group Handlers\n */\nexport class DragPanHandler {\n\n _el: HTMLElement;\n _mousePan: MousePanHandler;\n _touchPan: TouchPanHandler;\n _inertiaOptions: DragPanOptions | boolean;\n\n /** @internal */\n constructor(el: HTMLElement, mousePan: MousePanHandler, touchPan: TouchPanHandler) {\n this._el = el;\n this._mousePan = mousePan;\n this._touchPan = touchPan;\n }\n\n /**\n * Enables the \"drag to pan\" interaction.\n *\n * @param options - Options object\n * @example\n * ```ts\n * map.dragPan.enable();\n * map.dragPan.enable({\n * linearity: 0.3,\n * easing: bezier(0, 0, 0.3, 1),\n * maxSpeed: 1400,\n * deceleration: 2500,\n * });\n * ```\n */\n enable(options?: DragPanOptions | boolean) {\n this._inertiaOptions = options || {};\n this._mousePan.enable();\n this._touchPan.enable();\n this._el.classList.add('maplibregl-touch-drag-pan');\n }\n\n /**\n * Disables the \"drag to pan\" interaction.\n *\n * @example\n * ```ts\n * map.dragPan.disable();\n * ```\n */\n disable() {\n this._mousePan.disable();\n this._touchPan.disable();\n this._el.classList.remove('maplibregl-touch-drag-pan');\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to pan\" interaction is enabled.\n *\n * @returns `true` if the \"drag to pan\" interaction is enabled.\n */\n isEnabled() {\n return this._mousePan.isEnabled() && this._touchPan.isEnabled();\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to pan\" interaction is active, i.e. currently being used.\n *\n * @returns `true` if the \"drag to pan\" interaction is active.\n */\n isActive() {\n return this._mousePan.isActive() || this._touchPan.isActive();\n }\n}\n","import type {MousePitchHandler, MouseRotateHandler} from '../mouse';\n\n/**\n * Options object for `DragRotateHandler`.\n */\nexport type DragRotateHandlerOptions = {\n /**\n * Control the map pitch in addition to the bearing\n * @defaultValue true\n */\n pitchWithRotate: boolean;\n}\n\n/**\n * The `DragRotateHandler` allows the user to rotate the map by clicking and\n * dragging the cursor while holding the right mouse button or `ctrl` key.\n *\n * @group Handlers\n */\nexport class DragRotateHandler {\n\n _mouseRotate: MouseRotateHandler;\n _mousePitch: MousePitchHandler;\n _pitchWithRotate: boolean;\n\n /** @internal */\n constructor(options: DragRotateHandlerOptions, mouseRotate: MouseRotateHandler, mousePitch: MousePitchHandler) {\n this._pitchWithRotate = options.pitchWithRotate;\n this._mouseRotate = mouseRotate;\n this._mousePitch = mousePitch;\n }\n\n /**\n * Enables the \"drag to rotate\" interaction.\n *\n * @example\n * ```ts\n * map.dragRotate.enable();\n * ```\n */\n enable() {\n this._mouseRotate.enable();\n if (this._pitchWithRotate) this._mousePitch.enable();\n }\n\n /**\n * Disables the \"drag to rotate\" interaction.\n *\n * @example\n * ```ts\n * map.dragRotate.disable();\n * ```\n */\n disable() {\n this._mouseRotate.disable();\n this._mousePitch.disable();\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to rotate\" interaction is enabled.\n *\n * @returns `true` if the \"drag to rotate\" interaction is enabled.\n */\n isEnabled() {\n return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled());\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to rotate\" interaction is active, i.e. currently being used.\n *\n * @returns `true` if the \"drag to rotate\" interaction is active.\n */\n isActive() {\n return this._mouseRotate.isActive() || this._mousePitch.isActive();\n }\n}\n","import type {TwoFingersTouchZoomHandler, TwoFingersTouchRotateHandler, AroundCenterOptions} from '../two_fingers_touch';\nimport type {TapDragZoomHandler} from '../tap_drag_zoom';\n\n/**\n * The `TwoFingersTouchZoomRotateHandler` allows the user to zoom and rotate the map by\n * pinching on a touchscreen.\n *\n * They can zoom with one finger by double tapping and dragging. On the second tap,\n * hold the finger down and drag up or down to zoom in or out.\n *\n * @group Handlers\n */\nexport class TwoFingersTouchZoomRotateHandler {\n\n _el: HTMLElement;\n _touchZoom: TwoFingersTouchZoomHandler;\n _touchRotate: TwoFingersTouchRotateHandler;\n _tapDragZoom: TapDragZoomHandler;\n _rotationDisabled: boolean;\n _enabled: boolean;\n\n /** @internal */\n constructor(el: HTMLElement, touchZoom: TwoFingersTouchZoomHandler, touchRotate: TwoFingersTouchRotateHandler, tapDragZoom: TapDragZoomHandler) {\n this._el = el;\n this._touchZoom = touchZoom;\n this._touchRotate = touchRotate;\n this._tapDragZoom = tapDragZoom;\n this._rotationDisabled = false;\n this._enabled = true;\n }\n\n /**\n * Enables the \"pinch to rotate and zoom\" interaction.\n *\n * @param options - Options object.\n *\n * @example\n * ```ts\n * map.touchZoomRotate.enable();\n * map.touchZoomRotate.enable({ around: 'center' });\n * ```\n */\n enable(options?: AroundCenterOptions | boolean | null) {\n this._touchZoom.enable(options);\n if (!this._rotationDisabled) this._touchRotate.enable(options);\n this._tapDragZoom.enable();\n this._el.classList.add('maplibregl-touch-zoom-rotate');\n }\n\n /**\n * Disables the \"pinch to rotate and zoom\" interaction.\n *\n * @example\n * ```ts\n * map.touchZoomRotate.disable();\n * ```\n */\n disable() {\n this._touchZoom.disable();\n this._touchRotate.disable();\n this._tapDragZoom.disable();\n this._el.classList.remove('maplibregl-touch-zoom-rotate');\n }\n\n /**\n * Returns a Boolean indicating whether the \"pinch to rotate and zoom\" interaction is enabled.\n *\n * @returns `true` if the \"pinch to rotate and zoom\" interaction is enabled.\n */\n isEnabled() {\n return this._touchZoom.isEnabled() &&\n (this._rotationDisabled || this._touchRotate.isEnabled()) &&\n this._tapDragZoom.isEnabled();\n }\n\n /**\n * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture.\n *\n * @returns `true` if the handler is active, `false` otherwise\n */\n isActive() {\n return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive();\n }\n\n /**\n * Disables the \"pinch to rotate\" interaction, leaving the \"pinch to zoom\"\n * interaction enabled.\n *\n * @example\n * ```ts\n * map.touchZoomRotate.disableRotation();\n * ```\n */\n disableRotation() {\n this._rotationDisabled = true;\n this._touchRotate.disable();\n }\n\n /**\n * Enables the \"pinch to rotate\" interaction.\n *\n * @example\n * ```ts\n * map.touchZoomRotate.enable();\n * map.touchZoomRotate.enableRotation();\n * ```\n */\n enableRotation() {\n this._rotationDisabled = false;\n if (this._touchZoom.isEnabled()) this._touchRotate.enable();\n }\n}\n","import {DOM} from '../../util/dom';\nimport {Event} from '../../util/evented';\nimport {Handler} from '../handler_manager';\n\nimport type {Map} from '../map';\n\n/**\n * The {@link CooperativeGesturesHandler} options object for the gesture settings\n */\nexport type GestureOptions = boolean;\n\n/**\n * A `CooperativeGestureHandler` is a control that adds cooperative gesture info when user tries to zoom in/out.\n *\n * When the CooperativeGestureHandler blocks a gesture, it will emit a `cooperativegestureprevented` event.\n *\n * @group Handlers\n *\n * @example\n * ```ts\n * const map = new Map({\n * cooperativeGestures: true\n * });\n * ```\n * @see [Example: cooperative gestures](https://maplibre.org/maplibre-gl-js/docs/examples/cooperative-gestures/)\n **/\nexport class CooperativeGesturesHandler implements Handler {\n _options: GestureOptions;\n _map: Map;\n _container: HTMLElement;\n /**\n * This is the key that will allow to bypass the cooperative gesture protection\n */\n _bypassKey: 'metaKey' | 'ctrlKey' = navigator.userAgent.indexOf('Mac') !== -1 ? 'metaKey' : 'ctrlKey';\n _enabled: boolean;\n\n constructor(map: Map, options: GestureOptions) {\n this._map = map;\n this._options = options;\n this._enabled = false;\n }\n isActive(): boolean {\n return false;\n }\n reset(): void {}\n\n _setupUI() {\n if (this._container) return;\n const mapCanvasContainer = this._map.getCanvasContainer();\n // Add a cooperative gestures class (enable touch-action: pan-x pan-y;)\n mapCanvasContainer.classList.add('maplibregl-cooperative-gestures');\n this._container = DOM.create('div', 'maplibregl-cooperative-gesture-screen', mapCanvasContainer);\n let desktopMessage = this._map._getUIString('CooperativeGesturesHandler.WindowsHelpText');\n if (this._bypassKey === 'metaKey') {\n desktopMessage = this._map._getUIString('CooperativeGesturesHandler.MacHelpText');\n }\n const mobileMessage = this._map._getUIString('CooperativeGesturesHandler.MobileHelpText');\n // Create and append the desktop message div\n const desktopDiv = document.createElement('div');\n desktopDiv.className = 'maplibregl-desktop-message';\n desktopDiv.textContent = desktopMessage;\n this._container.appendChild(desktopDiv);\n // Create and append the mobile message div\n const mobileDiv = document.createElement('div');\n mobileDiv.className = 'maplibregl-mobile-message';\n mobileDiv.textContent = mobileMessage;\n this._container.appendChild(mobileDiv);\n // Remove cooperative gesture screen from the accessibility tree since screenreaders cannot interact with the map using gestures\n this._container.setAttribute('aria-hidden', 'true');\n }\n\n _destroyUI() {\n if (this._container) {\n DOM.remove(this._container);\n const mapCanvasContainer = this._map.getCanvasContainer();\n mapCanvasContainer.classList.remove('maplibregl-cooperative-gestures');\n }\n delete this._container;\n }\n\n enable() {\n this._setupUI();\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this._destroyUI();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isBypassed(event: MouseEvent | WheelEvent | PointerEvent) {\n return event[this._bypassKey];\n }\n\n notifyGestureBlocked(gestureType: 'wheel_zoom' | 'touch_pan', originalEvent: Event) {\n if (!this._enabled) return;\n\n // notify subscribers that a cooperative gesture was prevented\n this._map.fire(new Event('cooperativegestureprevented', {gestureType, originalEvent}));\n\n // Alert user how to scroll/pan\n this._container.classList.add('maplibregl-show');\n setTimeout(() => {\n this._container.classList.remove('maplibregl-show');\n }, 100);\n }\n}\n","import {Event} from '../util/evented';\nimport {DOM} from '../util/dom';\nimport {Map, CompleteMapOptions} from './map';\nimport {HandlerInertia} from './handler_inertia';\nimport {MapEventHandler, BlockableMapEventHandler} from './handler/map_event';\nimport {BoxZoomHandler} from './handler/box_zoom';\nimport {TapZoomHandler} from './handler/tap_zoom';\nimport {generateMouseRotationHandler, generateMousePitchHandler, generateMousePanHandler} from './handler/mouse';\nimport {TouchPanHandler} from './handler/touch_pan';\nimport {TwoFingersTouchZoomHandler, TwoFingersTouchRotateHandler, TwoFingersTouchPitchHandler} from './handler/two_fingers_touch';\nimport {KeyboardHandler} from './handler/keyboard';\nimport {ScrollZoomHandler} from './handler/scroll_zoom';\nimport {DoubleClickZoomHandler} from './handler/shim/dblclick_zoom';\nimport {ClickZoomHandler} from './handler/click_zoom';\nimport {TapDragZoomHandler} from './handler/tap_drag_zoom';\nimport {DragPanHandler} from './handler/shim/drag_pan';\nimport {DragRotateHandler} from './handler/shim/drag_rotate';\nimport {TwoFingersTouchZoomRotateHandler} from './handler/shim/two_fingers_touch';\nimport {CooperativeGesturesHandler} from './handler/cooperative_gestures';\nimport {extend} from '../util/util';\nimport {browser} from '../util/browser';\nimport Point from '@mapbox/point-geometry';\n\nconst isMoving = (p: EventsInProgress) => p.zoom || p.drag || p.pitch || p.rotate;\n\nclass RenderFrameEvent extends Event {\n type: 'renderFrame';\n timeStamp: number;\n}\n\n/**\n * Handlers interpret dom events and return camera changes that should be\n * applied to the map (`HandlerResult`s). The camera changes are all deltas.\n * The handler itself should have no knowledge of the map's current state.\n * This makes it easier to merge multiple results and keeps handlers simpler.\n * For example, if there is a mousedown and mousemove, the mousePan handler\n * would return a `panDelta` on the mousemove.\n */\nexport interface Handler {\n enable(): void;\n disable(): void;\n isEnabled(): boolean;\n /**\n * This is used to indicate if the handler is currently active or not.\n * In case a handler is active, it will block other handlers from getting the relevant events.\n * There is an allow list of handlers that can be active at the same time, which is configured when adding a handler.\n */\n isActive(): boolean;\n /**\n * `reset` can be called by the manager at any time and must reset everything to it's original state\n */\n reset(): void;\n // Handlers can optionally implement these methods.\n // They are called with dom events whenever those dom evens are received.\n readonly touchstart?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void;\n readonly touchmove?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void;\n readonly touchmoveWindow?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void;\n readonly touchend?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void;\n readonly touchcancel?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void;\n readonly mousedown?: (e: MouseEvent, point: Point) => HandlerResult | void;\n readonly mousemove?: (e: MouseEvent, point: Point) => HandlerResult | void;\n readonly mousemoveWindow?: (e: MouseEvent, point: Point) => HandlerResult | void;\n readonly mouseup?: (e: MouseEvent, point: Point) => HandlerResult | void;\n readonly mouseupWindow?: (e: MouseEvent, point: Point) => HandlerResult | void;\n readonly dblclick?: (e: MouseEvent, point: Point) => HandlerResult | void;\n readonly contextmenu?: (e: MouseEvent) => HandlerResult | void;\n readonly wheel?: (e: WheelEvent, point: Point) => HandlerResult | void;\n readonly keydown?: (e: KeyboardEvent) => HandlerResult | void;\n readonly keyup?: (e: KeyboardEvent) => HandlerResult | void;\n /**\n * `renderFrame` is the only non-dom event. It is called during render\n * frames and can be used to smooth camera changes (see scroll handler).\n */\n readonly renderFrame?: () => HandlerResult | void;\n}\n\n/**\n * All handler methods that are called with events can optionally return a `HandlerResult`.\n */\nexport type HandlerResult = {\n panDelta?: Point;\n zoomDelta?: number;\n bearingDelta?: number;\n pitchDelta?: number;\n /**\n * the point to not move when changing the camera\n */\n around?: Point | null;\n /**\n * same as above, except for pinch actions, which are given higher priority\n */\n pinchAround?: Point | null;\n /**\n * A method that can fire a one-off easing by directly changing the map's camera.\n */\n cameraAnimation?: (map: Map) => any;\n /**\n * The last three properties are needed by only one handler: scrollzoom.\n * The DOM event to be used as the `originalEvent` on any camera change events.\n */\n originalEvent?: Event;\n /**\n * Makes the manager trigger a frame, allowing the handler to return multiple results over time (see scrollzoom).\n */\n needsRenderFrame?: boolean;\n /**\n * The camera changes won't get recorded for inertial zooming.\n */\n noInertia?: boolean;\n};\n\nexport type EventInProgress = {\n handlerName: string;\n originalEvent: Event;\n}\n\nexport type EventsInProgress = {\n zoom?: EventInProgress;\n pitch?: EventInProgress;\n rotate?: EventInProgress;\n drag?: EventInProgress;\n}\n\nfunction hasChange(result: HandlerResult) {\n return (result.panDelta && result.panDelta.mag()) || result.zoomDelta || result.bearingDelta || result.pitchDelta;\n}\n\nexport class HandlerManager {\n _map: Map;\n _el: HTMLElement;\n _handlers: Array<{\n handlerName: string;\n handler: Handler;\n allowed: Array;\n }>;\n _eventsInProgress: EventsInProgress;\n _frameId: number;\n _inertia: HandlerInertia;\n _bearingSnap: number;\n _handlersById: {[x: string]: Handler};\n _updatingCamera: boolean;\n _changes: Array<[HandlerResult, EventsInProgress, {[handlerName: string]: Event}]>;\n _terrainMovement: boolean;\n _zoom: {handlerName: string};\n _previousActiveHandlers: {[x: string]: Handler};\n _listeners: Array<[Window | Document | HTMLElement, string, {\n passive?: boolean;\n capture?: boolean;\n } | undefined]>;\n\n constructor(map: Map, options: CompleteMapOptions) {\n this._map = map;\n this._el = this._map.getCanvasContainer();\n this._handlers = [];\n this._handlersById = {};\n this._changes = [];\n\n this._inertia = new HandlerInertia(map);\n this._bearingSnap = options.bearingSnap;\n this._previousActiveHandlers = {};\n\n // Track whether map is currently moving, to compute start/move/end events\n this._eventsInProgress = {};\n\n this._addDefaultHandlers(options);\n\n const el = this._el;\n\n this._listeners = [\n // This needs to be `passive: true` so that a double tap fires two\n // pairs of touchstart/end events in iOS Safari 13. If this is set to\n // `passive: false` then the second pair of events is only fired if\n // preventDefault() is called on the first touchstart. Calling preventDefault()\n // undesirably prevents click events.\n [el, 'touchstart', {passive: true}],\n // This needs to be `passive: false` so that scrolls and pinches can be\n // prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12.\n [el, 'touchmove', {passive: false}],\n [el, 'touchend', undefined],\n [el, 'touchcancel', undefined],\n\n [el, 'mousedown', undefined],\n [el, 'mousemove', undefined],\n [el, 'mouseup', undefined],\n\n // Bind window-level event listeners for move and up/end events. In the absence of\n // the pointer capture API, which is not supported by all necessary platforms,\n // window-level event listeners give us the best shot at capturing events that\n // fall outside the map canvas element. Use `{capture: true}` for the move event\n // to prevent map move events from being fired during a drag.\n [document, 'mousemove', {capture: true}],\n [document, 'mouseup', undefined],\n\n [el, 'mouseover', undefined],\n [el, 'mouseout', undefined],\n [el, 'dblclick', undefined],\n [el, 'click', undefined],\n\n [el, 'keydown', {capture: false}],\n [el, 'keyup', undefined],\n\n [el, 'wheel', {passive: false}],\n [el, 'contextmenu', undefined],\n\n [window, 'blur', undefined]\n ];\n\n for (const [target, type, listenerOptions] of this._listeners) {\n DOM.addEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions);\n }\n }\n\n destroy() {\n for (const [target, type, listenerOptions] of this._listeners) {\n DOM.removeEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions);\n }\n }\n\n _addDefaultHandlers(options: CompleteMapOptions) {\n const map = this._map;\n const el = map.getCanvasContainer();\n this._add('mapEvent', new MapEventHandler(map, options));\n\n const boxZoom = map.boxZoom = new BoxZoomHandler(map, options);\n this._add('boxZoom', boxZoom);\n if (options.interactive && options.boxZoom) {\n boxZoom.enable();\n }\n\n const cooperativeGestures = map.cooperativeGestures = new CooperativeGesturesHandler(map, options.cooperativeGestures);\n this._add('cooperativeGestures', cooperativeGestures);\n if (options.cooperativeGestures) {\n cooperativeGestures.enable();\n }\n\n const tapZoom = new TapZoomHandler(map);\n const clickZoom = new ClickZoomHandler(map);\n map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom);\n this._add('tapZoom', tapZoom);\n this._add('clickZoom', clickZoom);\n if (options.interactive && options.doubleClickZoom) {\n map.doubleClickZoom.enable();\n }\n\n const tapDragZoom = new TapDragZoomHandler();\n this._add('tapDragZoom', tapDragZoom);\n\n const touchPitch = map.touchPitch = new TwoFingersTouchPitchHandler(map);\n this._add('touchPitch', touchPitch);\n if (options.interactive && options.touchPitch) {\n map.touchPitch.enable(options.touchPitch);\n }\n\n const mouseRotate = generateMouseRotationHandler(options);\n const mousePitch = generateMousePitchHandler(options);\n map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch);\n this._add('mouseRotate', mouseRotate, ['mousePitch']);\n this._add('mousePitch', mousePitch, ['mouseRotate']);\n if (options.interactive && options.dragRotate) {\n map.dragRotate.enable();\n }\n\n const mousePan = generateMousePanHandler(options);\n const touchPan = new TouchPanHandler(options, map);\n map.dragPan = new DragPanHandler(el, mousePan, touchPan);\n this._add('mousePan', mousePan);\n this._add('touchPan', touchPan, ['touchZoom', 'touchRotate']);\n if (options.interactive && options.dragPan) {\n map.dragPan.enable(options.dragPan);\n }\n\n const touchRotate = new TwoFingersTouchRotateHandler();\n const touchZoom = new TwoFingersTouchZoomHandler();\n map.touchZoomRotate = new TwoFingersTouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom);\n this._add('touchRotate', touchRotate, ['touchPan', 'touchZoom']);\n this._add('touchZoom', touchZoom, ['touchPan', 'touchRotate']);\n if (options.interactive && options.touchZoomRotate) {\n map.touchZoomRotate.enable(options.touchZoomRotate);\n }\n\n const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, () => this._triggerRenderFrame());\n this._add('scrollZoom', scrollZoom, ['mousePan']);\n if (options.interactive && options.scrollZoom) {\n map.scrollZoom.enable(options.scrollZoom);\n }\n\n const keyboard = map.keyboard = new KeyboardHandler(map);\n this._add('keyboard', keyboard);\n if (options.interactive && options.keyboard) {\n map.keyboard.enable();\n }\n\n this._add('blockableMapEvent', new BlockableMapEventHandler(map));\n }\n\n _add(handlerName: string, handler: Handler, allowed?: Array) {\n this._handlers.push({handlerName, handler, allowed});\n this._handlersById[handlerName] = handler;\n }\n\n stop(allowEndAnimation: boolean) {\n // do nothing if this method was triggered by a gesture update\n if (this._updatingCamera) return;\n\n for (const {handler} of this._handlers) {\n handler.reset();\n }\n this._inertia.clear();\n this._fireEvents({}, {}, allowEndAnimation);\n this._changes = [];\n }\n\n isActive() {\n for (const {handler} of this._handlers) {\n if (handler.isActive()) return true;\n }\n return false;\n }\n\n isZooming() {\n return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming();\n }\n isRotating() {\n return !!this._eventsInProgress.rotate;\n }\n\n isMoving() {\n return Boolean(isMoving(this._eventsInProgress)) || this.isZooming();\n }\n\n _blockedByActive(activeHandlers: {[x: string]: Handler}, allowed: Array, myName: string) {\n for (const name in activeHandlers) {\n if (name === myName) continue;\n if (!allowed || allowed.indexOf(name) < 0) {\n return true;\n }\n }\n return false;\n }\n\n handleWindowEvent = (e: { type: 'mousemove' | 'mouseup' | 'touchmove'}) => {\n this.handleEvent(e, `${e.type}Window`);\n };\n\n _getMapTouches(touches: TouchList) {\n const mapTouches = [];\n for (const t of touches) {\n const target = (t.target as any as Node);\n if (this._el.contains(target)) {\n mapTouches.push(t);\n }\n }\n return mapTouches as any as TouchList;\n }\n\n handleEvent = (e: Event, eventName?: keyof Handler) => {\n\n if (e.type === 'blur') {\n this.stop(true);\n return;\n }\n\n this._updatingCamera = true;\n\n const inputEvent = e.type === 'renderFrame' ? undefined : e as UIEvent;\n\n /*\n * We don't call e.preventDefault() for any events by default.\n * Handlers are responsible for calling it where necessary.\n */\n\n const mergedHandlerResult: HandlerResult = {needsRenderFrame: false};\n const eventsInProgress: EventsInProgress = {};\n const activeHandlers = {};\n const eventTouches = (e as TouchEvent).touches;\n\n const mapTouches = eventTouches ? this._getMapTouches(eventTouches) : undefined;\n const points = mapTouches ?\n DOM.touchPos(this._map.getCanvas(), mapTouches) :\n DOM.mousePos(this._map.getCanvas(), ((e as MouseEvent)));\n\n for (const {handlerName, handler, allowed} of this._handlers) {\n if (!handler.isEnabled()) continue;\n\n let data: HandlerResult;\n if (this._blockedByActive(activeHandlers, allowed, handlerName)) {\n handler.reset();\n\n } else {\n if (handler[eventName || e.type]) {\n data = handler[eventName || e.type](e, points, mapTouches);\n this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent);\n if (data && data.needsRenderFrame) {\n this._triggerRenderFrame();\n }\n }\n }\n\n if (data || handler.isActive()) {\n activeHandlers[handlerName] = handler;\n }\n }\n\n const deactivatedHandlers: {[handlerName: string]: Event} = {};\n for (const name in this._previousActiveHandlers) {\n if (!activeHandlers[name]) {\n deactivatedHandlers[name] = inputEvent;\n }\n }\n this._previousActiveHandlers = activeHandlers;\n\n if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) {\n this._changes.push([mergedHandlerResult, eventsInProgress, deactivatedHandlers]);\n this._triggerRenderFrame();\n }\n\n if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) {\n this._map._stop(true);\n }\n\n this._updatingCamera = false;\n\n const {cameraAnimation} = mergedHandlerResult;\n if (cameraAnimation) {\n this._inertia.clear();\n this._fireEvents({}, {}, true);\n this._changes = [];\n cameraAnimation(this._map);\n }\n };\n\n mergeHandlerResult(mergedHandlerResult: HandlerResult,\n eventsInProgress: EventsInProgress,\n handlerResult: HandlerResult,\n name: string,\n e?: UIEvent) {\n if (!handlerResult) return;\n\n extend(mergedHandlerResult, handlerResult);\n\n const eventData = {handlerName: name, originalEvent: handlerResult.originalEvent || e};\n\n // track which handler changed which camera property\n if (handlerResult.zoomDelta !== undefined) {\n eventsInProgress.zoom = eventData;\n }\n if (handlerResult.panDelta !== undefined) {\n eventsInProgress.drag = eventData;\n }\n if (handlerResult.pitchDelta !== undefined) {\n eventsInProgress.pitch = eventData;\n }\n if (handlerResult.bearingDelta !== undefined) {\n eventsInProgress.rotate = eventData;\n }\n\n }\n\n _applyChanges() {\n const combined: HandlerResult = {};\n const combinedEventsInProgress: EventsInProgress = {};\n const combinedDeactivatedHandlers = {};\n\n for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) {\n\n if (change.panDelta) combined.panDelta = (combined.panDelta || new Point(0, 0))._add(change.panDelta);\n if (change.zoomDelta) combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta;\n if (change.bearingDelta) combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta;\n if (change.pitchDelta) combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta;\n if (change.around !== undefined) combined.around = change.around;\n if (change.pinchAround !== undefined) combined.pinchAround = change.pinchAround;\n if (change.noInertia) combined.noInertia = change.noInertia;\n\n extend(combinedEventsInProgress, eventsInProgress);\n extend(combinedDeactivatedHandlers, deactivatedHandlers);\n }\n\n this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers);\n this._changes = [];\n }\n\n _updateMapTransform(combinedResult: HandlerResult,\n combinedEventsInProgress: EventsInProgress,\n deactivatedHandlers: {[handlerName: string]: Event}) {\n const map = this._map;\n const tr = map._getTransformForUpdate();\n const terrain = map.terrain;\n\n if (!hasChange(combinedResult) && !(terrain && this._terrainMovement)) {\n return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);\n }\n\n let {panDelta, zoomDelta, bearingDelta, pitchDelta, around, pinchAround} = combinedResult;\n\n if (pinchAround !== undefined) {\n around = pinchAround;\n }\n\n // stop any ongoing camera animations (easeTo, flyTo)\n map._stop(true);\n\n around = around || map.transform.centerPoint;\n const loc = tr.pointLocation(panDelta ? around.sub(panDelta) : around);\n if (bearingDelta) tr.bearing += bearingDelta;\n if (pitchDelta) tr.pitch += pitchDelta;\n if (zoomDelta) tr.zoom += zoomDelta;\n\n if (!terrain) {\n tr.setLocationAtPoint(loc, around);\n } else {\n // when 3d-terrain is enabled act a little different:\n // - dragging do not drag the picked point itself, instead it drags the map by pixel-delta.\n // With this approach it is no longer possible to pick a point from somewhere near\n // the horizon to the center in one move.\n // So this logic avoids the problem, that in such cases you easily loose orientation.\n if (!this._terrainMovement &&\n (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) {\n // When starting to drag or move, flag it and register moveend to clear flagging\n this._terrainMovement = true;\n this._map._elevationFreeze = true;\n tr.setLocationAtPoint(loc, around);\n } else if (combinedEventsInProgress.drag && this._terrainMovement) {\n // drag map\n tr.center = tr.pointLocation(tr.centerPoint.sub(panDelta));\n } else {\n tr.setLocationAtPoint(loc, around);\n }\n }\n\n map._applyUpdatedTransform(tr);\n\n this._map._update();\n if (!combinedResult.noInertia) this._inertia.record(combinedResult);\n this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);\n\n }\n\n _fireEvents(newEventsInProgress: EventsInProgress, deactivatedHandlers: {[handlerName: string]: Event}, allowEndAnimation: boolean) {\n\n const wasMoving = isMoving(this._eventsInProgress);\n const nowMoving = isMoving(newEventsInProgress);\n\n const startEvents = {};\n\n for (const eventName in newEventsInProgress) {\n const {originalEvent} = newEventsInProgress[eventName];\n if (!this._eventsInProgress[eventName]) {\n startEvents[`${eventName}start`] = originalEvent;\n }\n this._eventsInProgress[eventName] = newEventsInProgress[eventName];\n }\n\n // fire start events only after this._eventsInProgress has been updated\n if (!wasMoving && nowMoving) {\n this._fireEvent('movestart', nowMoving.originalEvent);\n }\n\n for (const name in startEvents) {\n this._fireEvent(name, startEvents[name]);\n }\n\n if (nowMoving) {\n this._fireEvent('move', nowMoving.originalEvent);\n }\n\n for (const eventName in newEventsInProgress) {\n const {originalEvent} = newEventsInProgress[eventName];\n this._fireEvent(eventName, originalEvent);\n }\n\n const endEvents = {};\n\n let originalEndEvent;\n for (const eventName in this._eventsInProgress) {\n const {handlerName, originalEvent} = this._eventsInProgress[eventName];\n if (!this._handlersById[handlerName].isActive()) {\n delete this._eventsInProgress[eventName];\n originalEndEvent = deactivatedHandlers[handlerName] || originalEvent;\n endEvents[`${eventName}end`] = originalEndEvent;\n }\n }\n\n for (const name in endEvents) {\n this._fireEvent(name, endEvents[name]);\n }\n\n const stillMoving = isMoving(this._eventsInProgress);\n const finishedMoving = (wasMoving || nowMoving) && !stillMoving;\n if (finishedMoving && this._terrainMovement) {\n this._map._elevationFreeze = false;\n this._terrainMovement = false;\n const tr = this._map._getTransformForUpdate();\n tr.recalculateZoom(this._map.terrain);\n this._map._applyUpdatedTransform(tr);\n }\n if (allowEndAnimation && finishedMoving) {\n this._updatingCamera = true;\n const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions);\n\n const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap;\n\n if (inertialEase && (inertialEase.essential || !browser.prefersReducedMotion)) {\n if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) {\n inertialEase.bearing = 0;\n }\n inertialEase.freezeElevation = true;\n this._map.easeTo(inertialEase, {originalEvent: originalEndEvent});\n } else {\n this._map.fire(new Event('moveend', {originalEvent: originalEndEvent}));\n if (shouldSnapToNorth(this._map.getBearing())) {\n this._map.resetNorth();\n }\n }\n this._updatingCamera = false;\n }\n\n }\n\n _fireEvent(type: string, e?: Event) {\n this._map.fire(new Event(type, e ? {originalEvent: e} : {}));\n }\n\n _requestFrame() {\n this._map.triggerRepaint();\n return this._map._renderTaskQueue.add(timeStamp => {\n delete this._frameId;\n this.handleEvent(new RenderFrameEvent('renderFrame', {timeStamp}));\n this._applyChanges();\n });\n }\n\n _triggerRenderFrame() {\n if (this._frameId === undefined) {\n this._frameId = this._requestFrame();\n }\n }\n}\n","import {extend, warnOnce, clamp, wrap, defaultEasing, pick, degreesToRadians} from '../util/util';\nimport {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {browser} from '../util/browser';\nimport {LngLat} from '../geo/lng_lat';\nimport {LngLatBounds} from '../geo/lng_lat_bounds';\nimport Point from '@mapbox/point-geometry';\nimport {Event, Evented} from '../util/evented';\nimport {Terrain} from '../render/terrain';\nimport {MercatorCoordinate} from '../geo/mercator_coordinate';\n\nimport type {Transform} from '../geo/transform';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport type {LngLatBoundsLike} from '../geo/lng_lat_bounds';\nimport type {TaskID} from '../util/task_queue';\nimport type {PaddingOptions} from '../geo/edge_insets';\nimport type {HandlerManager} from './handler_manager';\n/**\n * A [Point](https://github.com/mapbox/point-geometry) or an array of two numbers representing `x` and `y` screen coordinates in pixels.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let p1 = new Point(-77, 38); // a PointLike which is a Point\n * let p2 = [-77, 38]; // a PointLike which is an array of two numbers\n * ```\n */\nexport type PointLike = Point | [number, number];\n\n/**\n * A helper to allow require of at least one property\n */\nexport type RequireAtLeastOne = { [K in keyof T]-?: Required> & Partial>>; }[keyof T];\n\n/**\n * Options common to {@link Map#jumpTo}, {@link Map#easeTo}, and {@link Map#flyTo}, controlling the desired location,\n * zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current\n * camera value for that property will remain unchanged.\n *\n * @example\n * Set the map's initial perspective with CameraOptions\n * ```ts\n * let map = new Map({\n * container: 'map',\n * style: 'https://demotiles.maplibre.org/style.json',\n * center: [-73.5804, 45.53483],\n * pitch: 60,\n * bearing: -60,\n * zoom: 10\n * });\n * ```\n * @see [Set pitch and bearing](https://maplibre.org/maplibre-gl-js/docs/examples/set-perspective/)\n * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to/)\n * @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto/)\n * @see [Display buildings in 3D](https://maplibre.org/maplibre-gl-js/docs/examples/3d-buildings/)\n */\nexport type CameraOptions = CenterZoomBearing & {\n /**\n * The desired pitch in degrees. The pitch is the angle towards the horizon\n * measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance\n * of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon.\n * Increasing the pitch value is often used to display 3D objects.\n */\n pitch?: number;\n /**\n * If `zoom` is specified, `around` determines the point around which the zoom is centered.\n */\n around?: LngLatLike;\n};\n\n/**\n * Holds center, zoom and bearing properties\n */\nexport type CenterZoomBearing = {\n /**\n * The desired center.\n */\n center?: LngLatLike;\n /**\n * The desired zoom level.\n */\n zoom?: number;\n /**\n * The desired bearing in degrees. The bearing is the compass direction that\n * is \"up\". For example, `bearing: 90` orients the map so that east is up.\n */\n bearing?: number;\n}\n\n/**\n * The options object related to the {@link Map#jumpTo} method\n */\nexport type JumpToOptions = CameraOptions & {\n /**\n * Dimensions in pixels applied on each side of the viewport for shifting the vanishing point.\n */\n padding?: PaddingOptions;\n}\n\n/**\n * A options object for the {@link Map#cameraForBounds} method\n */\nexport type CameraForBoundsOptions = CameraOptions & {\n /**\n * The amount of padding in pixels to add to the given bounds.\n */\n padding?: number | RequireAtLeastOne;\n /**\n * The center of the given bounds relative to the map's center, measured in pixels.\n * @defaultValue [0, 0]\n */\n offset?: PointLike;\n /**\n * The maximum zoom level to allow when the camera would transition to the specified bounds.\n */\n maxZoom?: number;\n}\n\n/**\n * The {@link Map#flyTo} options object\n */\nexport type FlyToOptions = AnimationOptions & CameraOptions & {\n /**\n * The zooming \"curve\" that will occur along the\n * flight path. A high value maximizes zooming for an exaggerated animation, while a low\n * value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average\n * value selected by participants in the user study discussed in\n * [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of\n * `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A\n * value of 1 would produce a circular motion.\n * @defaultValue 1.42\n */\n curve?: number;\n /**\n * The zero-based zoom level at the peak of the flight path. If\n * `options.curve` is specified, this option is ignored.\n */\n minZoom?: number;\n /**\n * The average speed of the animation defined in relation to\n * `options.curve`. A speed of 1.2 means that the map appears to move along the flight path\n * by 1.2 times `options.curve` screenfuls every second. A _screenful_ is the map's visible span.\n * It does not correspond to a fixed physical distance, but varies by zoom level.\n * @defaultValue 1.2\n */\n speed?: number;\n /**\n * The average speed of the animation measured in screenfuls\n * per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored.\n */\n screenSpeed?: number;\n /**\n * The animation's maximum duration, measured in milliseconds.\n * If duration exceeds maximum duration, it resets to 0.\n */\n maxDuration?: number;\n /**\n * The amount of padding in pixels to add to the given bounds.\n */\n padding?: number | RequireAtLeastOne;\n}\n\nexport type EaseToOptions = AnimationOptions & CameraOptions & {\n delayEndEvents?: number;\n padding?: number | RequireAtLeastOne;\n}\n\n/**\n * Options for {@link Map#fitBounds} method\n */\nexport type FitBoundsOptions = FlyToOptions & {\n /**\n * If `true`, the map transitions using {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}.\n * See those functions and {@link AnimationOptions} for information about options available.\n * @defaultValue false\n */\n linear?: boolean;\n /**\n * The center of the given bounds relative to the map's center, measured in pixels.\n * @defaultValue [0, 0]\n */\n offset?: PointLike;\n /**\n * The maximum zoom level to allow when the map view transitions to the specified bounds.\n */\n maxZoom?: number;\n}\n\n/**\n * Options common to map movement methods that involve animation, such as {@link Map#panBy} and\n * {@link Map#easeTo}, controlling the duration and easing function of the animation. All properties\n * are optional.\n *\n */\nexport type AnimationOptions = {\n /**\n * The animation's duration, measured in milliseconds.\n */\n duration?: number;\n /**\n * A function taking a time in the range 0..1 and returning a number where 0 is\n * the initial state and 1 is the final state.\n */\n easing?: (_: number) => number;\n /**\n * of the target center relative to real map container center at the end of animation.\n */\n offset?: PointLike;\n /**\n * If `false`, no animation will occur.\n */\n animate?: boolean;\n /**\n * If `true`, then the animation is considered essential and will not be affected by\n * [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/\\@media/prefers-reduced-motion).\n */\n essential?: boolean;\n /**\n * Default false. Needed in 3D maps to let the camera stay in a constant\n * height based on sea-level. After the animation finished the zoom-level will be recalculated in respect of\n * the distance from the camera to the center-coordinate-altitude.\n */\n freezeElevation?: boolean;\n};\n\n/**\n * A callback hook that allows manipulating the camera and being notified about camera updates before they happen\n */\nexport type CameraUpdateTransformFunction = (next: {\n center: LngLat;\n zoom: number;\n pitch: number;\n bearing: number;\n elevation: number;\n}) => {\n center?: LngLat;\n zoom?: number;\n pitch?: number;\n bearing?: number;\n elevation?: number;\n};\n\nexport abstract class Camera extends Evented {\n transform: Transform;\n terrain: Terrain;\n handlers: HandlerManager;\n\n _moving: boolean;\n _zooming: boolean;\n _rotating: boolean;\n _pitching: boolean;\n _padding: boolean;\n\n _bearingSnap: number;\n _easeStart: number;\n _easeOptions: {\n duration?: number;\n easing?: (_: number) => number;\n };\n _easeId: string | void;\n\n _onEaseFrame: (_: number) => void;\n _onEaseEnd: (easeId?: string) => void;\n _easeFrameId: TaskID;\n\n /**\n * @internal\n * holds the geographical coordinate of the target\n */\n _elevationCenter: LngLat;\n /**\n * @internal\n * holds the targ altitude value, = center elevation of the target.\n * This value may changes during flight, because new terrain-tiles loads during flight.\n */\n _elevationTarget: number;\n /**\n * @internal\n * holds the start altitude value, = center elevation before animation begins\n * this value will recalculated during flight in respect of changing _elevationTarget values,\n * so the linear interpolation between start and target keeps smooth and without jumps.\n */\n _elevationStart: number;\n /**\n * @internal\n * Saves the current state of the elevation freeze - this is used during map movement to prevent \"rocky\" camera movement.\n */\n _elevationFreeze: boolean;\n /**\n * @internal\n * Used to track accumulated changes during continuous interaction\n */\n _requestedCameraState?: Transform;\n /**\n * A callback used to defer camera updates or apply arbitrary constraints.\n * If specified, this Camera instance can be used as a stateless component in React etc.\n */\n transformCameraUpdate: CameraUpdateTransformFunction | null;\n\n abstract _requestRenderFrame(a: () => void): TaskID;\n abstract _cancelRenderFrame(_: TaskID): void;\n\n constructor(transform: Transform, options: {\n bearingSnap: number;\n }) {\n super();\n this._moving = false;\n this._zooming = false;\n this.transform = transform;\n this._bearingSnap = options.bearingSnap;\n\n this.on('moveend', () => {\n delete this._requestedCameraState;\n });\n }\n\n /**\n * Returns the map's geographical centerpoint.\n *\n * @returns The map's geographical centerpoint.\n * @example\n * Return a LngLat object such as `{lng: 0, lat: 0}`\n * ```ts\n * let center = map.getCenter();\n * // access longitude and latitude values directly\n * let {lng, lat} = map.getCenter();\n * ```\n */\n getCenter(): LngLat { return new LngLat(this.transform.center.lng, this.transform.center.lat); }\n\n /**\n * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`.\n *\n * Triggers the following events: `movestart` and `moveend`.\n *\n * @param center - The centerpoint to set.\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * ```ts\n * map.setCenter([-74, 38]);\n * ```\n */\n setCenter(center: LngLatLike, eventData?: any) {\n return this.jumpTo({center}, eventData);\n }\n\n /**\n * Pans the map by the specified offset.\n *\n * Triggers the following events: `movestart` and `moveend`.\n *\n * @param offset - `x` and `y` coordinates by which to pan the map.\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/)\n */\n panBy(offset: PointLike, options?: AnimationOptions, eventData?: any): this {\n offset = Point.convert(offset).mult(-1);\n return this.panTo(this.transform.center, extend({offset}, options), eventData);\n }\n\n /**\n * Pans the map to the specified location with an animated transition.\n *\n * Triggers the following events: `movestart` and `moveend`.\n *\n * @param lnglat - The location to pan the map to.\n * @param options - Options describing the destination and animation of the transition.\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * ```ts\n * map.panTo([-74, 38]);\n * // Specify that the panTo animation should last 5000 milliseconds.\n * map.panTo([-74, 38], {duration: 5000});\n * ```\n * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/)\n */\n panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: any): this {\n return this.easeTo(extend({\n center: lnglat\n }, options), eventData);\n }\n\n /**\n * Returns the map's current zoom level.\n *\n * @returns The map's current zoom level.\n * @example\n * ```ts\n * map.getZoom();\n * ```\n */\n getZoom(): number { return this.transform.zoom; }\n\n /**\n * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n *\n * @param zoom - The zoom level to set (0-20).\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * Zoom to the zoom level 5 without an animated transition\n * ```ts\n * map.setZoom(5);\n * ```\n */\n setZoom(zoom: number, eventData?: any): this {\n this.jumpTo({zoom}, eventData);\n return this;\n }\n\n /**\n * Zooms the map to the specified zoom level, with an animated transition.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n *\n * @param zoom - The zoom level to transition to.\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * ```ts\n * // Zoom to the zoom level 5 without an animated transition\n * map.zoomTo(5);\n * // Zoom to the zoom level 8 with an animated transition\n * map.zoomTo(8, {\n * duration: 2000,\n * offset: [100, 50]\n * });\n * ```\n */\n zoomTo(zoom: number, options?: AnimationOptions | null, eventData?: any): this {\n return this.easeTo(extend({\n zoom\n }, options), eventData);\n }\n\n /**\n * Increases the map's zoom level by 1.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n *\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * Zoom the map in one level with a custom animation duration\n * ```ts\n * map.zoomIn({duration: 1000});\n * ```\n */\n zoomIn(options?: AnimationOptions, eventData?: any): this {\n this.zoomTo(this.getZoom() + 1, options, eventData);\n return this;\n }\n\n /**\n * Decreases the map's zoom level by 1.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n *\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * Zoom the map out one level with a custom animation offset\n * ```ts\n * map.zoomOut({offset: [80, 60]});\n * ```\n */\n zoomOut(options?: AnimationOptions, eventData?: any): this {\n this.zoomTo(this.getZoom() - 1, options, eventData);\n return this;\n }\n\n /**\n * Returns the map's current bearing. The bearing is the compass direction that is \"up\"; for example, a bearing\n * of 90° orients the map so that east is up.\n *\n * @returns The map's current bearing.\n * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/)\n */\n getBearing(): number { return this.transform.bearing; }\n\n /**\n * Sets the map's bearing (rotation). The bearing is the compass direction that is \"up\"; for example, a bearing\n * of 90° orients the map so that east is up.\n *\n * Equivalent to `jumpTo({bearing: bearing})`.\n *\n * Triggers the following events: `movestart`, `moveend`, and `rotate`.\n *\n * @param bearing - The desired bearing.\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * Rotate the map to 90 degrees\n * ```ts\n * map.setBearing(90);\n * ```\n */\n setBearing(bearing: number, eventData?: any): this {\n this.jumpTo({bearing}, eventData);\n return this;\n }\n\n /**\n * Returns the current padding applied around the map viewport.\n *\n * @returns The current padding around the map viewport.\n */\n getPadding(): PaddingOptions { return this.transform.padding; }\n\n /**\n * Sets the padding in pixels around the viewport.\n *\n * Equivalent to `jumpTo({padding: padding})`.\n *\n * Triggers the following events: `movestart` and `moveend`.\n *\n * @param padding - The desired padding.\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * Sets a left padding of 300px, and a top padding of 50px\n * ```ts\n * map.setPadding({ left: 300, top: 50 });\n * ```\n */\n setPadding(padding: PaddingOptions, eventData?: any): this {\n this.jumpTo({padding}, eventData);\n return this;\n }\n\n /**\n * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction\n * that is \"up\"; for example, a bearing of 90° orients the map so that east is up.\n *\n * Triggers the following events: `movestart`, `moveend`, and `rotate`.\n *\n * @param bearing - The desired bearing.\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n */\n rotateTo(bearing: number, options?: AnimationOptions, eventData?: any): this {\n return this.easeTo(extend({\n bearing\n }, options), eventData);\n }\n\n /**\n * Rotates the map so that north is up (0° bearing), with an animated transition.\n *\n * Triggers the following events: `movestart`, `moveend`, and `rotate`.\n *\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n */\n resetNorth(options?: AnimationOptions, eventData?: any): this {\n this.rotateTo(0, extend({duration: 1000}, options), eventData);\n return this;\n }\n\n /**\n * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, `pitchend`, and `rotate`.\n *\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n */\n resetNorthPitch(options?: AnimationOptions, eventData?: any): this {\n this.easeTo(extend({\n bearing: 0,\n pitch: 0,\n duration: 1000\n }, options), eventData);\n return this;\n }\n\n /**\n * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the\n * `bearingSnap` threshold).\n *\n * Triggers the following events: `movestart`, `moveend`, and `rotate`.\n *\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n */\n snapToNorth(options?: AnimationOptions, eventData?: any): this {\n if (Math.abs(this.getBearing()) < this._bearingSnap) {\n return this.resetNorth(options, eventData);\n }\n return this;\n }\n\n /**\n * Returns the map's current pitch (tilt).\n *\n * @returns The map's current pitch, measured in degrees away from the plane of the screen.\n */\n getPitch(): number { return this.transform.pitch; }\n\n /**\n * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`.\n *\n * Triggers the following events: `movestart`, `moveend`, `pitchstart`, and `pitchend`.\n *\n * @param pitch - The pitch to set, measured in degrees away from the plane of the screen (0-60).\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n */\n setPitch(pitch: number, eventData?: any): this {\n this.jumpTo({pitch}, eventData);\n return this;\n }\n\n /**\n * @param bounds - Calculate the center for these bounds in the viewport and use\n * the highest zoom level up to and including `Map#getMaxZoom()` that fits\n * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0.\n * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point.\n * @param options - Options object\n * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`.\n * If map is unable to fit, method will warn and return undefined.\n * @example\n * ```ts\n * let bbox = [[-79, 43], [-73, 45]];\n * let newCameraTransform = map.cameraForBounds(bbox, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * ```\n */\n cameraForBounds(bounds: LngLatBoundsLike, options?: CameraForBoundsOptions): CenterZoomBearing | undefined {\n bounds = LngLatBounds.convert(bounds).adjustAntiMeridian();\n const bearing = options && options.bearing || 0;\n\n return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options);\n }\n\n /**\n * @internal\n * Calculate the center of these two points in the viewport and use\n * the highest zoom level up to and including `Map#getMaxZoom()` that fits\n * the points in the viewport at the specified bearing.\n * @param p0 - First point\n * @param p1 - Second point\n * @param bearing - Desired map bearing at end of animation, in degrees\n * @param options - the camera options\n * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`.\n * If map is unable to fit, method will warn and return undefined.\n * @example\n * ```ts\n * let p0 = [-79, 43];\n * let p1 = [-73, 45];\n * let bearing = 90;\n * let newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * ```\n */\n _cameraForBoxAndBearing(p0: LngLatLike, p1: LngLatLike, bearing: number, options?: CameraForBoundsOptions): CenterZoomBearing | undefined {\n const defaultPadding = {\n top: 0,\n bottom: 0,\n right: 0,\n left: 0\n };\n options = extend({\n padding: defaultPadding,\n offset: [0, 0],\n maxZoom: this.transform.maxZoom\n }, options);\n\n if (typeof options.padding === 'number') {\n const p = options.padding;\n options.padding = {\n top: p,\n bottom: p,\n right: p,\n left: p\n };\n }\n\n options.padding = extend(defaultPadding, options.padding) as PaddingOptions;\n const tr = this.transform;\n const edgePadding = tr.padding;\n\n // Consider all corners of the rotated bounding box derived from the given points\n // when find the camera position that fits the given points.\n const bounds = new LngLatBounds(p0, p1);\n const nwWorld = tr.project(bounds.getNorthWest());\n const neWorld = tr.project(bounds.getNorthEast());\n const seWorld = tr.project(bounds.getSouthEast());\n const swWorld = tr.project(bounds.getSouthWest());\n\n const bearingRadians = degreesToRadians(-bearing);\n\n const nwRotatedWorld = nwWorld.rotate(bearingRadians);\n const neRotatedWorld = neWorld.rotate(bearingRadians);\n const seRotatedWorld = seWorld.rotate(bearingRadians);\n const swRotatedWorld = swWorld.rotate(bearingRadians);\n\n const upperRight = new Point(\n Math.max(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x),\n Math.max(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)\n );\n\n const lowerLeft = new Point(\n Math.min(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x),\n Math.min(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)\n );\n\n // Calculate zoom: consider the original bbox and padding.\n const size = upperRight.sub(lowerLeft);\n const scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x;\n const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y;\n\n if (scaleY < 0 || scaleX < 0) {\n warnOnce(\n 'Map cannot fit within canvas with the given bounds, padding, and/or offset.'\n );\n return undefined;\n }\n\n const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom);\n\n // Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of padding.\n const offset = Point.convert(options.offset);\n const paddingOffsetX = (options.padding.left - options.padding.right) / 2;\n const paddingOffsetY = (options.padding.top - options.padding.bottom) / 2;\n const paddingOffset = new Point(paddingOffsetX, paddingOffsetY);\n const rotatedPaddingOffset = paddingOffset.rotate(degreesToRadians(bearing));\n const offsetAtInitialZoom = offset.add(rotatedPaddingOffset);\n const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom));\n\n const center = tr.unproject(\n // either world diagonal can be used (NW-SE or NE-SW)\n nwWorld.add(seWorld).div(2).sub(offsetAtFinalZoom)\n );\n\n return {\n center,\n zoom,\n bearing\n };\n }\n\n /**\n * Pans and zooms the map to contain its visible area within the specified geographical bounds.\n * This function will also reset the map's bearing to 0 if bearing is nonzero.\n *\n * Triggers the following events: `movestart` and `moveend`.\n *\n * @param bounds - Center these bounds in the viewport and use the highest\n * zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport.\n * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point.\n * @param options - Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below.\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * ```ts\n * let bbox = [[-79, 43], [-73, 45]];\n * map.fitBounds(bbox, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * ```\n * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fitbounds/)\n */\n fitBounds(bounds: LngLatBoundsLike, options?: FitBoundsOptions, eventData?: any): this {\n return this._fitInternal(\n this.cameraForBounds(bounds, options),\n options,\n eventData);\n }\n\n /**\n * Pans, rotates and zooms the map to to fit the box made by points p0 and p1\n * once the map is rotated to the specified bearing. To zoom without rotating,\n * pass in the current map bearing.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend` and `rotate`.\n *\n * @param p0 - First point on screen, in pixel coordinates\n * @param p1 - Second point on screen, in pixel coordinates\n * @param bearing - Desired map bearing at end of animation, in degrees\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * ```ts\n * let p0 = [220, 400];\n * let p1 = [500, 900];\n * map.fitScreenCoordinates(p0, p1, map.getBearing(), {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * ```\n * @see Used by {@link BoxZoomHandler}\n */\n fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: FitBoundsOptions, eventData?: any): this {\n return this._fitInternal(\n this._cameraForBoxAndBearing(\n this.transform.pointLocation(Point.convert(p0)),\n this.transform.pointLocation(Point.convert(p1)),\n bearing,\n options),\n options,\n eventData);\n }\n\n _fitInternal(calculatedOptions?: CenterZoomBearing, options?: FitBoundsOptions, eventData?: any): this {\n // cameraForBounds warns + returns undefined if unable to fit:\n if (!calculatedOptions) return this;\n\n options = extend(calculatedOptions, options);\n // Explicitly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly.\n delete options.padding;\n\n return options.linear ?\n this.easeTo(options, eventData) :\n this.flyTo(options, eventData);\n }\n\n /**\n * Changes any combination of center, zoom, bearing, and pitch, without\n * an animated transition. The map will retain its current values for any\n * details not specified in `options`.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,\n * `pitch`, `pitchend`, and `rotate`.\n *\n * @param options - Options object\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * ```ts\n * // jump to coordinates at current zoom\n * map.jumpTo({center: [0, 0]});\n * // jump with zoom, pitch, and bearing options\n * map.jumpTo({\n * center: [0, 0],\n * zoom: 8,\n * pitch: 45,\n * bearing: 90\n * });\n * ```\n * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to/)\n * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/)\n */\n jumpTo(options: JumpToOptions, eventData?: any): this {\n this.stop();\n\n const tr = this._getTransformForUpdate();\n let zoomChanged = false,\n bearingChanged = false,\n pitchChanged = false;\n\n if ('zoom' in options && tr.zoom !== +options.zoom) {\n zoomChanged = true;\n tr.zoom = +options.zoom;\n }\n\n if (options.center !== undefined) {\n tr.center = LngLat.convert(options.center);\n }\n\n if ('bearing' in options && tr.bearing !== +options.bearing) {\n bearingChanged = true;\n tr.bearing = +options.bearing;\n }\n\n if ('pitch' in options && tr.pitch !== +options.pitch) {\n pitchChanged = true;\n tr.pitch = +options.pitch;\n }\n\n if (options.padding != null && !tr.isPaddingEqual(options.padding)) {\n tr.padding = options.padding;\n }\n this._applyUpdatedTransform(tr);\n\n this.fire(new Event('movestart', eventData))\n .fire(new Event('move', eventData));\n\n if (zoomChanged) {\n this.fire(new Event('zoomstart', eventData))\n .fire(new Event('zoom', eventData))\n .fire(new Event('zoomend', eventData));\n }\n\n if (bearingChanged) {\n this.fire(new Event('rotatestart', eventData))\n .fire(new Event('rotate', eventData))\n .fire(new Event('rotateend', eventData));\n }\n\n if (pitchChanged) {\n this.fire(new Event('pitchstart', eventData))\n .fire(new Event('pitch', eventData))\n .fire(new Event('pitchend', eventData));\n }\n\n return this.fire(new Event('moveend', eventData));\n }\n\n /**\n * Calculates pitch, zoom and bearing for looking at `newCenter` with the camera position being `newCenter`\n * and returns them as {@link CameraOptions}.\n * @param from - The camera to look from\n * @param altitudeFrom - The altitude of the camera to look from\n * @param to - The center to look at\n * @param altitudeTo - Optional altitude of the center to look at. If none given the ground height will be used.\n * @returns the calculated camera options\n */\n calculateCameraOptionsFromTo(from: LngLat, altitudeFrom: number, to: LngLat, altitudeTo: number = 0): CameraOptions {\n const fromMerc = MercatorCoordinate.fromLngLat(from, altitudeFrom);\n const toMerc = MercatorCoordinate.fromLngLat(to, altitudeTo);\n const dx = toMerc.x - fromMerc.x;\n const dy = toMerc.y - fromMerc.y;\n const dz = toMerc.z - fromMerc.z;\n\n const distance3D = Math.hypot(dx, dy, dz);\n if (distance3D === 0) throw new Error('Can\\'t calculate camera options with same From and To');\n\n const groundDistance = Math.hypot(dx, dy);\n\n const zoom = this.transform.scaleZoom(this.transform.cameraToCenterDistance / distance3D / this.transform.tileSize);\n const bearing = (Math.atan2(dx, -dy) * 180) / Math.PI;\n let pitch = (Math.acos(groundDistance / distance3D) * 180) / Math.PI;\n pitch = dz < 0 ? 90 - pitch : 90 + pitch;\n\n return {\n center: toMerc.toLngLat(),\n zoom,\n pitch,\n bearing\n };\n }\n\n /**\n * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition\n * between old and new values. The map will retain its current values for any\n * details not specified in `options`.\n *\n * Note: The transition will happen instantly if the user has enabled\n * the `reduced motion` accessibility feature enabled in their operating system,\n * unless `options` includes `essential: true`.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,\n * `pitch`, `pitchend`, and `rotate`.\n *\n * @param options - Options describing the destination and animation of the transition.\n * Accepts {@link CameraOptions} and {@link AnimationOptions}.\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/)\n */\n easeTo(options: EaseToOptions & {\n easeId?: string;\n noMoveStart?: boolean;\n }, eventData?: any): this {\n this._stop(false, options.easeId);\n\n options = extend({\n offset: [0, 0],\n duration: 500,\n easing: defaultEasing\n }, options);\n\n if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) options.duration = 0;\n\n const tr = this._getTransformForUpdate(),\n startZoom = tr.zoom,\n startBearing = tr.bearing,\n startPitch = tr.pitch,\n startPadding = tr.padding,\n\n bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing,\n pitch = 'pitch' in options ? +options.pitch : startPitch,\n padding = 'padding' in options ? options.padding : tr.padding;\n\n const offsetAsPoint = Point.convert(options.offset);\n let pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n const locationAtOffset = tr.pointLocation(pointAtOffset);\n\n const {center, zoom} = tr.getConstrained(\n LngLat.convert(options.center || locationAtOffset),\n options.zoom ?? startZoom\n );\n this._normalizeCenter(center, tr);\n\n const from = tr.project(locationAtOffset);\n const delta = tr.project(center).sub(from);\n const finalScale = tr.zoomScale(zoom - startZoom);\n\n let around, aroundPoint;\n\n if (options.around) {\n around = LngLat.convert(options.around);\n aroundPoint = tr.locationPoint(around);\n }\n\n const currently = {\n moving: this._moving,\n zooming: this._zooming,\n rotating: this._rotating,\n pitching: this._pitching\n };\n\n this._zooming = this._zooming || (zoom !== startZoom);\n this._rotating = this._rotating || (startBearing !== bearing);\n this._pitching = this._pitching || (pitch !== startPitch);\n this._padding = !tr.isPaddingEqual(padding as PaddingOptions);\n\n this._easeId = options.easeId;\n this._prepareEase(eventData, options.noMoveStart, currently);\n if (this.terrain) this._prepareElevation(center);\n\n this._ease((k) => {\n if (this._zooming) {\n tr.zoom = interpolates.number(startZoom, zoom, k);\n }\n if (this._rotating) {\n tr.bearing = interpolates.number(startBearing, bearing, k);\n }\n if (this._pitching) {\n tr.pitch = interpolates.number(startPitch, pitch, k);\n }\n if (this._padding) {\n tr.interpolatePadding(startPadding, padding as PaddingOptions, k);\n // When padding is being applied, Transform#centerPoint is changing continuously,\n // thus we need to recalculate offsetPoint every frame\n pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n }\n\n if (this.terrain && !options.freezeElevation) this._updateElevation(k);\n\n if (around) {\n tr.setLocationAtPoint(around, aroundPoint);\n } else {\n const scale = tr.zoomScale(tr.zoom - startZoom);\n const base = zoom > startZoom ?\n Math.min(2, finalScale) :\n Math.max(0.5, finalScale);\n const speedup = Math.pow(base, 1 - k);\n const newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale));\n tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);\n }\n\n this._applyUpdatedTransform(tr);\n\n this._fireMoveEvents(eventData);\n\n }, (interruptingEaseId?: string) => {\n if (this.terrain && options.freezeElevation) this._finalizeElevation();\n this._afterEase(eventData, interruptingEaseId);\n }, options as any);\n\n return this;\n }\n\n _prepareEase(eventData: any, noMoveStart: boolean, currently: any = {}) {\n this._moving = true;\n if (!noMoveStart && !currently.moving) {\n this.fire(new Event('movestart', eventData));\n }\n if (this._zooming && !currently.zooming) {\n this.fire(new Event('zoomstart', eventData));\n }\n if (this._rotating && !currently.rotating) {\n this.fire(new Event('rotatestart', eventData));\n }\n if (this._pitching && !currently.pitching) {\n this.fire(new Event('pitchstart', eventData));\n }\n }\n\n _prepareElevation(center: LngLat) {\n this._elevationCenter = center;\n this._elevationStart = this.transform.elevation;\n this._elevationTarget = this.terrain.getElevationForLngLatZoom(center, this.transform.tileZoom);\n this._elevationFreeze = true;\n }\n\n _updateElevation(k: number) {\n this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom);\n const elevation = this.terrain.getElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom);\n // target terrain updated during flight, slowly move camera to new height\n if (k < 1 && elevation !== this._elevationTarget) {\n const pitch1 = this._elevationTarget - this._elevationStart;\n const pitch2 = (elevation - (pitch1 * k + this._elevationStart)) / (1 - k);\n this._elevationStart += k * (pitch1 - pitch2);\n this._elevationTarget = elevation;\n }\n this.transform.elevation = interpolates.number(this._elevationStart, this._elevationTarget, k);\n }\n\n _finalizeElevation() {\n this._elevationFreeze = false;\n this.transform.recalculateZoom(this.terrain);\n }\n\n /**\n * @internal\n * Called when the camera is about to be manipulated.\n * If `transformCameraUpdate` is specified or terrain is enabled, a copy of\n * the current transform is created to track the accumulated changes.\n * This underlying transform represents the \"desired state\" proposed by input handlers / animations / UI controls.\n * It may differ from the state used for rendering (`this.transform`).\n * @returns Transform to apply changes to\n */\n _getTransformForUpdate(): Transform {\n if (!this.transformCameraUpdate && !this.terrain) return this.transform;\n\n if (!this._requestedCameraState) {\n this._requestedCameraState = this.transform.clone();\n }\n return this._requestedCameraState;\n }\n\n /**\n * @internal\n * Checks the given transform for the camera being below terrain surface and\n * returns new pitch and zoom to fix that.\n *\n * With the new pitch and zoom, the camera will be at the same ground\n * position but at higher altitude. It will still point to the same spot on\n * the map.\n *\n * @param tr - The transform to check.\n */\n _elevateCameraIfInsideTerrain(tr: Transform) : { pitch?: number; zoom?: number } {\n const camera = tr.getCameraPosition();\n const minAltitude = this.terrain.getElevationForLngLatZoom(camera.lngLat, tr.zoom);\n if (camera.altitude < minAltitude) {\n const newCamera = this.calculateCameraOptionsFromTo(\n camera.lngLat, minAltitude, tr.center, tr.elevation);\n return {\n pitch: newCamera.pitch,\n zoom: newCamera.zoom,\n };\n }\n return {};\n }\n\n /**\n * @internal\n * Called after the camera is done being manipulated.\n * @param tr - the requested camera end state\n * If the camera is inside terrain, it gets elevated.\n * Call `transformCameraUpdate` if present, and then apply the \"approved\" changes.\n */\n _applyUpdatedTransform(tr: Transform) {\n const modifiers : ((tr: Transform) => ReturnType)[] = [];\n if (this.terrain) {\n modifiers.push(tr => this._elevateCameraIfInsideTerrain(tr));\n }\n if (this.transformCameraUpdate) {\n modifiers.push(tr => this.transformCameraUpdate(tr));\n }\n if (!modifiers.length) {\n return;\n }\n const finalTransform = tr.clone();\n for (const modifier of modifiers) {\n const nextTransform = finalTransform.clone();\n const {\n center,\n zoom,\n pitch,\n bearing,\n elevation\n } = modifier(nextTransform);\n if (center) nextTransform.center = center;\n if (zoom !== undefined) nextTransform.zoom = zoom;\n if (pitch !== undefined) nextTransform.pitch = pitch;\n if (bearing !== undefined) nextTransform.bearing = bearing;\n if (elevation !== undefined) nextTransform.elevation = elevation;\n finalTransform.apply(nextTransform);\n }\n this.transform.apply(finalTransform);\n }\n\n _fireMoveEvents(eventData?: any) {\n this.fire(new Event('move', eventData));\n if (this._zooming) {\n this.fire(new Event('zoom', eventData));\n }\n if (this._rotating) {\n this.fire(new Event('rotate', eventData));\n }\n if (this._pitching) {\n this.fire(new Event('pitch', eventData));\n }\n }\n\n _afterEase(eventData?: any, easeId?: string) {\n // if this easing is being stopped to start another easing with\n // the same id then don't fire any events to avoid extra start/stop events\n if (this._easeId && easeId && this._easeId === easeId) {\n return;\n }\n delete this._easeId;\n\n const wasZooming = this._zooming;\n const wasRotating = this._rotating;\n const wasPitching = this._pitching;\n this._moving = false;\n this._zooming = false;\n this._rotating = false;\n this._pitching = false;\n this._padding = false;\n\n if (wasZooming) {\n this.fire(new Event('zoomend', eventData));\n }\n if (wasRotating) {\n this.fire(new Event('rotateend', eventData));\n }\n if (wasPitching) {\n this.fire(new Event('pitchend', eventData));\n }\n this.fire(new Event('moveend', eventData));\n }\n\n /**\n * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that\n * evokes flight. The animation seamlessly incorporates zooming and panning to help\n * the user maintain her bearings even after traversing a great distance.\n *\n * Note: The animation will be skipped, and this will behave equivalently to `jumpTo`\n * if the user has the `reduced motion` accessibility feature enabled in their operating system,\n * unless 'options' includes `essential: true`.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,\n * `pitch`, `pitchend`, and `rotate`.\n *\n * @param options - Options describing the destination and animation of the transition.\n * Accepts {@link CameraOptions}, {@link AnimationOptions},\n * and the following additional options.\n * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n * @example\n * ```ts\n * // fly with default options to null island\n * map.flyTo({center: [0, 0], zoom: 9});\n * // using flyTo options\n * map.flyTo({\n * center: [0, 0],\n * zoom: 9,\n * speed: 0.2,\n * curve: 1,\n * easing(t) {\n * return t;\n * }\n * });\n * ```\n * @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto/)\n * @see [Slowly fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto-options/)\n * @see [Fly to a location based on scroll position](https://maplibre.org/maplibre-gl-js/docs/examples/scroll-fly-to/)\n */\n flyTo(options: FlyToOptions, eventData?: any): this {\n // Fall through to jumpTo if user has set prefers-reduced-motion\n if (!options.essential && browser.prefersReducedMotion) {\n const coercedOptions = pick(options, ['center', 'zoom', 'bearing', 'pitch', 'around']) as CameraOptions;\n return this.jumpTo(coercedOptions, eventData);\n }\n\n // This method implements an “optimal path” animation, as detailed in:\n //\n // Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS\n // ’03. pp. 15–22. .\n //\n // Where applicable, local variable documentation begins with the associated variable or\n // function in van Wijk (2003).\n\n this.stop();\n\n options = extend({\n offset: [0, 0],\n speed: 1.2,\n curve: 1.42,\n easing: defaultEasing\n }, options);\n\n const tr = this._getTransformForUpdate(),\n startZoom = tr.zoom,\n startBearing = tr.bearing,\n startPitch = tr.pitch,\n startPadding = tr.padding;\n\n const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing;\n const pitch = 'pitch' in options ? +options.pitch : startPitch;\n const padding = 'padding' in options ? options.padding : tr.padding;\n\n const offsetAsPoint = Point.convert(options.offset);\n let pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n const locationAtOffset = tr.pointLocation(pointAtOffset);\n\n const {center, zoom} = tr.getConstrained(\n LngLat.convert(options.center || locationAtOffset),\n options.zoom ?? startZoom\n );\n this._normalizeCenter(center, tr);\n const scale = tr.zoomScale(zoom - startZoom);\n\n const from = tr.project(locationAtOffset);\n const delta = tr.project(center).sub(from);\n\n let rho = options.curve;\n\n // w₀: Initial visible span, measured in pixels at the initial scale.\n const w0 = Math.max(tr.width, tr.height),\n // w₁: Final visible span, measured in pixels with respect to the initial scale.\n w1 = w0 / scale,\n // Length of the flight path as projected onto the ground plane, measured in pixels from\n // the world image origin at the initial scale.\n u1 = delta.mag();\n\n if ('minZoom' in options) {\n const minZoom = clamp(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom);\n // wm: Maximum visible span, measured in pixels with respect to the initial\n // scale.\n const wMax = w0 / tr.zoomScale(minZoom - startZoom);\n rho = Math.sqrt(wMax / u1 * 2);\n }\n\n // ρ²\n const rho2 = rho * rho;\n\n /**\n * rᵢ: Returns the zoom-out factor at one end of the animation.\n *\n * @param descent - `true` for the descent, `false` for the ascent\n */\n function zoomOutFactor(descent: boolean) {\n const b = (w1 * w1 - w0 * w0 + (descent ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (descent ? w1 : w0) * rho2 * u1);\n return Math.log(Math.sqrt(b * b + 1) - b);\n }\n\n function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }\n function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }\n function tanh(n) { return sinh(n) / cosh(n); }\n\n // r₀: Zoom-out factor during ascent.\n const r0 = zoomOutFactor(false);\n\n // w(s): Returns the visible span on the ground, measured in pixels with respect to the\n // initial scale. Assumes an angular field of view of 2 arctan ½ ≈ 53°.\n let w: (_: number) => number = function (s) {\n return (cosh(r0) / cosh(r0 + rho * s));\n };\n\n // u(s): Returns the distance along the flight path as projected onto the ground plane,\n // measured in pixels from the world image origin at the initial scale.\n let u: (_: number) => number = function (s) {\n return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1;\n };\n\n // S: Total length of the flight path, measured in ρ-screenfuls.\n let S = (zoomOutFactor(true) - r0) / rho;\n\n // When u₀ = u₁, the optimal path doesn’t require both ascent and descent.\n if (Math.abs(u1) < 0.000001 || !isFinite(S)) {\n // Perform a more or less instantaneous transition if the path is too short.\n if (Math.abs(w0 - w1) < 0.000001) return this.easeTo(options, eventData);\n\n const k = w1 < w0 ? -1 : 1;\n S = Math.abs(Math.log(w1 / w0)) / rho;\n\n u = () => 0;\n w = (s) => Math.exp(k * rho * s);\n }\n\n if ('duration' in options) {\n options.duration = +options.duration;\n } else {\n const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed;\n options.duration = 1000 * S / V;\n }\n\n if (options.maxDuration && options.duration > options.maxDuration) {\n options.duration = 0;\n }\n\n this._zooming = true;\n this._rotating = (startBearing !== bearing);\n this._pitching = (pitch !== startPitch);\n this._padding = !tr.isPaddingEqual(padding as PaddingOptions);\n\n this._prepareEase(eventData, false);\n if (this.terrain) this._prepareElevation(center);\n\n this._ease((k) => {\n // s: The distance traveled along the flight path, measured in ρ-screenfuls.\n const s = k * S;\n const scale = 1 / w(s);\n tr.zoom = k === 1 ? zoom : startZoom + tr.scaleZoom(scale);\n\n if (this._rotating) {\n tr.bearing = interpolates.number(startBearing, bearing, k);\n }\n if (this._pitching) {\n tr.pitch = interpolates.number(startPitch, pitch, k);\n }\n if (this._padding) {\n tr.interpolatePadding(startPadding, padding as PaddingOptions, k);\n // When padding is being applied, Transform#centerPoint is changing continuously,\n // thus we need to recalculate offsetPoint every frame\n pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n }\n\n if (this.terrain && !options.freezeElevation) this._updateElevation(k);\n\n const newCenter = k === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale));\n tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);\n\n this._applyUpdatedTransform(tr);\n\n this._fireMoveEvents(eventData);\n\n }, () => {\n if (this.terrain && options.freezeElevation) this._finalizeElevation();\n this._afterEase(eventData);\n }, options);\n\n return this;\n }\n\n isEasing() {\n return !!this._easeFrameId;\n }\n\n /**\n * Stops any animated transition underway.\n */\n stop(): this {\n return this._stop();\n }\n\n _stop(allowGestures?: boolean, easeId?: string): this {\n if (this._easeFrameId) {\n this._cancelRenderFrame(this._easeFrameId);\n delete this._easeFrameId;\n delete this._onEaseFrame;\n }\n\n if (this._onEaseEnd) {\n // The _onEaseEnd function might emit events which trigger new\n // animation, which sets a new _onEaseEnd. Ensure we don't delete\n // it unintentionally.\n const onEaseEnd = this._onEaseEnd;\n delete this._onEaseEnd;\n onEaseEnd.call(this, easeId);\n }\n if (!allowGestures) {\n this.handlers?.stop(false);\n }\n return this;\n }\n\n _ease(frame: (_: number) => void,\n finish: () => void,\n options: {\n animate?: boolean;\n duration?: number;\n easing?: (_: number) => number;\n }) {\n if (options.animate === false || options.duration === 0) {\n frame(1);\n finish();\n } else {\n this._easeStart = browser.now();\n this._easeOptions = options;\n this._onEaseFrame = frame;\n this._onEaseEnd = finish;\n this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);\n }\n }\n\n // Callback for map._requestRenderFrame\n _renderFrameCallback = () => {\n const t = Math.min((browser.now() - this._easeStart) / this._easeOptions.duration, 1);\n this._onEaseFrame(this._easeOptions.easing(t));\n\n // if _stop is called during _onEaseFrame from _fireMoveEvents we should avoid a new _requestRenderFrame, checking it by ensuring _easeFrameId was not deleted\n if (t < 1 && this._easeFrameId) {\n this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);\n } else {\n this.stop();\n }\n };\n\n // convert bearing so that it's numerically close to the current one so that it interpolates properly\n _normalizeBearing(bearing: number, currentBearing: number) {\n bearing = wrap(bearing, -180, 180);\n const diff = Math.abs(bearing - currentBearing);\n if (Math.abs(bearing - 360 - currentBearing) < diff) bearing -= 360;\n if (Math.abs(bearing + 360 - currentBearing) < diff) bearing += 360;\n return bearing;\n }\n\n // If a path crossing the antimeridian would be shorter, extend the final coordinate so that\n // interpolating between the two endpoints will cross it.\n _normalizeCenter(center: LngLat, tr: Transform) {\n if (!tr.renderWorldCopies || tr.lngRange) return;\n\n const delta = center.lng - tr.center.lng;\n center.lng +=\n delta > 180 ? -360 :\n delta < -180 ? 360 : 0;\n }\n\n /**\n * Get the elevation difference between a given point\n * and a point that is currently in the middle of the screen.\n * This method should be used for proper positioning of custom 3d objects, as explained [here](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model-with-terrain/)\n * Returns null if terrain is not enabled.\n * This method is subject to change in Maplibre GL JS v5.\n * @param lngLatLike - [x,y] or LngLat coordinates of the location\n * @returns elevation offset in meters\n */\n queryTerrainElevation(lngLatLike: LngLatLike): number | null {\n if (!this.terrain) {\n return null;\n }\n const elevation = this.terrain.getElevationForLngLatZoom(LngLat.convert(lngLatLike), this.transform.tileZoom);\n return elevation - this.transform.elevation;\n }\n}\n","import {DOM} from '../../util/dom';\n\nimport type {Map} from '../map';\nimport type {ControlPosition, IControl} from './control';\nimport type {MapDataEvent} from '../events';\nimport type {StyleSpecification} from '@maplibre/maplibre-gl-style-spec';\n/**\n * The {@link AttributionControl} options object\n */\nexport type AttributionControlOptions = {\n /**\n * If `true`, the attribution control will always collapse when moving the map. If `false`,\n * force the expanded attribution control. The default is a responsive attribution that collapses when the user moves the map on maps less than 640 pixels wide.\n * **Attribution should not be collapsed if it can comfortably fit on the map. `compact` should only be used to modify default attribution when map size makes it impossible to fit default attribution and when the automatic compact resizing for default settings are not sufficient.**\n */\n compact?: boolean;\n /**\n * Attributions to show in addition to any other attributions.\n */\n customAttribution?: string | Array;\n};\n\nexport const defaultAttributionControlOptions: AttributionControlOptions = {\n compact: true,\n customAttribution: 'MapLibre'\n};\n\n/**\n * An `AttributionControl` control presents the map's attribution information. By default, the attribution control is expanded (regardless of map width).\n * @group Markers and Controls\n * @example\n * ```ts\n * let map = new Map({attributionControl: false})\n * .addControl(new AttributionControl({\n * compact: true\n * }));\n * ```\n */\nexport class AttributionControl implements IControl {\n options: AttributionControlOptions;\n _map: Map;\n _compact: boolean | undefined;\n _container: HTMLElement;\n _innerContainer: HTMLElement;\n _compactButton: HTMLElement;\n _editLink: HTMLAnchorElement;\n _attribHTML: string;\n styleId: string;\n styleOwner: string;\n\n /**\n * @param options - the attribution options\n */\n constructor(options: AttributionControlOptions = defaultAttributionControlOptions) {\n this.options = options;\n }\n\n getDefaultPosition(): ControlPosition {\n return 'bottom-right';\n }\n\n /** {@inheritDoc IControl.onAdd} */\n onAdd(map: Map) {\n this._map = map;\n this._compact = this.options.compact;\n this._container = DOM.create('details', 'maplibregl-ctrl maplibregl-ctrl-attrib');\n this._compactButton = DOM.create('summary', 'maplibregl-ctrl-attrib-button', this._container);\n this._compactButton.addEventListener('click', this._toggleAttribution);\n this._setElementTitle(this._compactButton, 'ToggleAttribution');\n this._innerContainer = DOM.create('div', 'maplibregl-ctrl-attrib-inner', this._container);\n\n this._updateAttributions();\n this._updateCompact();\n\n this._map.on('styledata', this._updateData);\n this._map.on('sourcedata', this._updateData);\n this._map.on('terrain', this._updateData);\n this._map.on('resize', this._updateCompact);\n this._map.on('drag', this._updateCompactMinimize);\n\n return this._container;\n }\n\n /** {@inheritDoc IControl.onRemove} */\n onRemove() {\n DOM.remove(this._container);\n\n this._map.off('styledata', this._updateData);\n this._map.off('sourcedata', this._updateData);\n this._map.off('terrain', this._updateData);\n this._map.off('resize', this._updateCompact);\n this._map.off('drag', this._updateCompactMinimize);\n\n this._map = undefined;\n this._compact = undefined;\n this._attribHTML = undefined;\n }\n\n _setElementTitle(element: HTMLElement, title: 'ToggleAttribution' | 'MapFeedback') {\n const str = this._map._getUIString(`AttributionControl.${title}`);\n element.title = str;\n element.setAttribute('aria-label', str);\n }\n\n _toggleAttribution = () => {\n if (this._container.classList.contains('maplibregl-compact')) {\n if (this._container.classList.contains('maplibregl-compact-show')) {\n this._container.setAttribute('open', '');\n this._container.classList.remove('maplibregl-compact-show');\n } else {\n this._container.classList.add('maplibregl-compact-show');\n this._container.removeAttribute('open');\n }\n }\n };\n\n _updateData = (e: MapDataEvent) => {\n if (e && (e.sourceDataType === 'metadata' || e.sourceDataType === 'visibility' || e.dataType === 'style' || e.type === 'terrain')) {\n this._updateAttributions();\n }\n };\n\n _updateAttributions() {\n if (!this._map.style) return;\n let attributions: Array = [];\n if (this.options.customAttribution) {\n if (Array.isArray(this.options.customAttribution)) {\n attributions = attributions.concat(\n this.options.customAttribution.map(attribution => {\n if (typeof attribution !== 'string') return '';\n return attribution;\n })\n );\n } else if (typeof this.options.customAttribution === 'string') {\n attributions.push(this.options.customAttribution);\n }\n }\n\n if (this._map.style.stylesheet) {\n const stylesheet = this._map.style.stylesheet as StyleSpecification & { owner: string; id: string };\n this.styleOwner = stylesheet.owner;\n this.styleId = stylesheet.id;\n }\n\n const sourceCaches = this._map.style.sourceCaches;\n for (const id in sourceCaches) {\n const sourceCache = sourceCaches[id];\n if (sourceCache.used || sourceCache.usedForTerrain) {\n const source = sourceCache.getSource();\n if (source.attribution && attributions.indexOf(source.attribution) < 0) {\n attributions.push(source.attribution);\n }\n }\n }\n\n // remove any entries that are whitespace\n attributions = attributions.filter(e => String(e).trim());\n\n // remove any entries that are substrings of another entry.\n // first sort by length so that substrings come first\n attributions.sort((a, b) => a.length - b.length);\n attributions = attributions.filter((attrib, i) => {\n for (let j = i + 1; j < attributions.length; j++) {\n if (attributions[j].indexOf(attrib) >= 0) { return false; }\n }\n return true;\n });\n\n // check if attribution string is different to minimize DOM changes\n const attribHTML = attributions.join(' | ');\n if (attribHTML === this._attribHTML) return;\n\n this._attribHTML = attribHTML;\n\n if (attributions.length) {\n this._innerContainer.innerHTML = attribHTML;\n this._container.classList.remove('maplibregl-attrib-empty');\n } else {\n this._container.classList.add('maplibregl-attrib-empty');\n }\n this._updateCompact();\n // remove old DOM node from _editLink\n this._editLink = null;\n }\n\n _updateCompact = () => {\n if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) {\n if (this._compact === false) {\n this._container.setAttribute('open', '');\n } else if (!this._container.classList.contains('maplibregl-compact') && !this._container.classList.contains('maplibregl-attrib-empty')) {\n this._container.setAttribute('open', '');\n this._container.classList.add('maplibregl-compact', 'maplibregl-compact-show');\n }\n } else {\n this._container.setAttribute('open', '');\n if (this._container.classList.contains('maplibregl-compact')) {\n this._container.classList.remove('maplibregl-compact', 'maplibregl-compact-show');\n }\n }\n };\n\n _updateCompactMinimize = () => {\n if (this._container.classList.contains('maplibregl-compact')) {\n if (this._container.classList.contains('maplibregl-compact-show')) {\n this._container.classList.remove('maplibregl-compact-show');\n }\n }\n };\n}\n","import {DOM} from '../../util/dom';\n\nimport type {Map} from '../map';\nimport type {ControlPosition, IControl} from './control';\n\n/**\n * The {@link LogoControl} options object\n */\ntype LogoControlOptions = {\n /**\n * If `true`, force a compact logo.\n * If `false`, force the full logo. The default is a responsive logo that collapses when the map is less than 640 pixels wide.\n */\n compact?: boolean;\n};\n\n/**\n * A `LogoControl` is a control that adds the watermark.\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * map.addControl(new LogoControl({compact: false}));\n * ```\n **/\nexport class LogoControl implements IControl {\n options: LogoControlOptions;\n _map: Map;\n _compact: boolean;\n _container: HTMLElement;\n\n /**\n * @param options - the control's options\n */\n constructor(options: LogoControlOptions = {}) {\n this.options = options;\n }\n\n getDefaultPosition(): ControlPosition {\n return 'bottom-left';\n }\n\n /** {@inheritDoc IControl.onAdd} */\n onAdd(map: Map) {\n this._map = map;\n this._compact = this.options && this.options.compact;\n this._container = DOM.create('div', 'maplibregl-ctrl');\n const anchor = DOM.create('a', 'maplibregl-ctrl-logo');\n anchor.target = '_blank';\n anchor.rel = 'noopener nofollow';\n anchor.href = 'https://maplibre.org/';\n anchor.setAttribute('aria-label', this._map._getUIString('LogoControl.Title'));\n anchor.setAttribute('rel', 'noopener nofollow');\n this._container.appendChild(anchor);\n this._container.style.display = 'block';\n\n this._map.on('resize', this._updateCompact);\n this._updateCompact();\n\n return this._container;\n }\n\n /** {@inheritDoc IControl.onRemove} */\n onRemove() {\n DOM.remove(this._container);\n this._map.off('resize', this._updateCompact);\n this._map = undefined;\n this._compact = undefined;\n }\n\n _updateCompact = () => {\n const containerChildren = this._container.children;\n if (containerChildren.length) {\n const anchor = containerChildren[0];\n if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) {\n if (this._compact !== false) {\n anchor.classList.add('maplibregl-compact');\n }\n } else {\n anchor.classList.remove('maplibregl-compact');\n }\n }\n };\n\n}\n","export type TaskID = number;\n\ntype Task = {\n callback: (timeStamp: number) => void;\n id: TaskID;\n cancelled: boolean;\n};\n\nexport class TaskQueue {\n _queue: Array;\n _id: TaskID;\n _cleared: boolean;\n _currentlyRunning: Array | false;\n\n constructor() {\n this._queue = [];\n this._id = 0;\n this._cleared = false;\n this._currentlyRunning = false;\n }\n\n add(callback: (timeStamp: number) => void): TaskID {\n const id = ++this._id;\n const queue = this._queue;\n queue.push({callback, id, cancelled: false});\n return id;\n }\n\n remove(id: TaskID) {\n const running = this._currentlyRunning;\n const queue = running ? this._queue.concat(running) : this._queue;\n for (const task of queue) {\n if (task.id === id) {\n task.cancelled = true;\n return;\n }\n }\n }\n\n run(timeStamp: number = 0) {\n if (this._currentlyRunning) throw new Error('Attempting to run(), but is already running.');\n const queue = this._currentlyRunning = this._queue;\n\n // Tasks queued by callbacks in the current queue should be executed\n // on the next run, not the current run.\n this._queue = [];\n\n for (const task of queue) {\n if (task.cancelled) continue;\n task.callback(timeStamp);\n if (this._cleared) break;\n }\n\n this._cleared = false;\n this._currentlyRunning = false;\n }\n\n clear() {\n if (this._currentlyRunning) {\n this._cleared = true;\n }\n this._queue = [];\n }\n}\n","import type {RequestParameters} from '../util/ajax';\n\nexport type PerformanceMetrics = {\n loadTime: number;\n fullLoadTime: number;\n fps: number;\n percentDroppedFrames: number;\n totalFrames: number;\n};\n\nexport enum PerformanceMarkers {\n create = 'create',\n load = 'load',\n fullLoad = 'fullLoad'\n}\n\nlet lastFrameTime = null;\nlet frameTimes = [];\n\nconst minFramerateTarget = 60;\nconst frameTimeTarget = 1000 / minFramerateTarget;\n\nconst loadTimeKey = 'loadTime';\nconst fullLoadTimeKey = 'fullLoadTime';\n\nexport const PerformanceUtils = {\n mark(marker: PerformanceMarkers) {\n performance.mark(marker);\n },\n frame(timestamp: number) {\n const currTimestamp = timestamp;\n if (lastFrameTime != null) {\n const frameTime = currTimestamp - lastFrameTime;\n frameTimes.push(frameTime);\n }\n lastFrameTime = currTimestamp;\n },\n clearMetrics() {\n lastFrameTime = null;\n frameTimes = [];\n performance.clearMeasures(loadTimeKey);\n performance.clearMeasures(fullLoadTimeKey);\n\n for (const marker in PerformanceMarkers) {\n performance.clearMarks(PerformanceMarkers[marker]);\n }\n },\n\n getPerformanceMetrics(): PerformanceMetrics {\n performance.measure(loadTimeKey, PerformanceMarkers.create, PerformanceMarkers.load);\n performance.measure(fullLoadTimeKey, PerformanceMarkers.create, PerformanceMarkers.fullLoad);\n const loadTime = performance.getEntriesByName(loadTimeKey)[0].duration;\n const fullLoadTime = performance.getEntriesByName(fullLoadTimeKey)[0].duration;\n const totalFrames = frameTimes.length;\n\n const avgFrameTime = frameTimes.reduce((prev, curr) => prev + curr, 0) / totalFrames / 1000;\n const fps = 1 / avgFrameTime;\n\n // count frames that missed our framerate target\n const droppedFrames = frameTimes\n .filter((frameTime) => frameTime > frameTimeTarget)\n .reduce((acc, curr) => {\n return acc + (curr - frameTimeTarget) / frameTimeTarget;\n }, 0);\n const percentDroppedFrames = (droppedFrames / (totalFrames + droppedFrames)) * 100;\n\n return {\n loadTime,\n fullLoadTime,\n fps,\n percentDroppedFrames,\n totalFrames\n };\n }\n};\n\n/**\n * @internal\n * Safe wrapper for the performance resource timing API in web workers with graceful degradation\n */\nexport class RequestPerformance {\n _marks: {\n start: string;\n end: string;\n measure: string;\n };\n\n constructor (request: RequestParameters) {\n this._marks = {\n start: [request.url, 'start'].join('#'),\n end: [request.url, 'end'].join('#'),\n measure: request.url.toString()\n };\n\n performance.mark(this._marks.start);\n }\n\n finish() {\n performance.mark(this._marks.end);\n let resourceTimingData = performance.getEntriesByName(this._marks.measure);\n\n // fallback if web worker implementation of perf.getEntriesByName returns empty\n if (resourceTimingData.length === 0) {\n performance.measure(this._marks.measure, this._marks.start, this._marks.end);\n resourceTimingData = performance.getEntriesByName(this._marks.measure);\n\n // cleanup\n performance.clearMarks(this._marks.start);\n performance.clearMarks(this._marks.end);\n performance.clearMeasures(this._marks.measure);\n }\n\n return resourceTimingData;\n }\n}\n\nexport default performance;\n","import {createLayout} from '../util/struct_array';\n\nexport default createLayout([\n {name: 'a_pos3d', type: 'Int16', components: 3}\n]);\n","import {OverscaledTileID} from './tile_id';\nimport {Tile} from './tile';\nimport {EXTENT} from '../data/extent';\nimport {mat4} from 'gl-matrix';\nimport {Evented} from '../util/evented';\nimport type {Transform} from '../geo/transform';\nimport type {SourceCache} from '../source/source_cache';\nimport {Terrain} from '../render/terrain';\n\n/**\n * @internal\n * This class is a helper for the Terrain-class, it:\n *\n * - loads raster-dem tiles\n * - manages all renderToTexture tiles.\n * - caches previous rendered tiles.\n * - finds all necessary renderToTexture tiles for a OverscaledTileID area\n * - finds the corresponding raster-dem tile for OverscaledTileID\n */\nexport class TerrainSourceCache extends Evented {\n /**\n * source-cache for the raster-dem source.\n */\n sourceCache: SourceCache;\n /**\n * stores all render-to-texture tiles.\n */\n _tiles: {[_: string]: Tile};\n /**\n * contains a list of tileID-keys for the current scene. (only for performance)\n */\n _renderableTilesKeys: Array;\n /**\n * raster-dem-tile for a TileID cache.\n */\n _sourceTileCache: {[_: string]: string};\n /**\n * minimum zoomlevel to render the terrain.\n */\n minzoom: number;\n /**\n * maximum zoomlevel to render the terrain.\n */\n maxzoom: number;\n /**\n * render-to-texture tileSize in scene.\n */\n tileSize: number;\n /**\n * raster-dem tiles will load for performance the actualZoom - deltaZoom zoom-level.\n */\n deltaZoom: number;\n\n constructor(sourceCache: SourceCache) {\n super();\n this.sourceCache = sourceCache;\n this._tiles = {};\n this._renderableTilesKeys = [];\n this._sourceTileCache = {};\n this.minzoom = 0;\n this.maxzoom = 22;\n this.tileSize = 512;\n this.deltaZoom = 1;\n sourceCache.usedForTerrain = true;\n sourceCache.tileSize = this.tileSize * 2 ** this.deltaZoom;\n }\n\n destruct() {\n this.sourceCache.usedForTerrain = false;\n this.sourceCache.tileSize = null;\n }\n\n /**\n * Load Terrain Tiles, create internal render-to-texture tiles, free GPU memory.\n * @param transform - the operation to do\n * @param terrain - the terrain\n */\n update(transform: Transform, terrain: Terrain): void {\n // load raster-dem tiles for the current scene.\n this.sourceCache.update(transform, terrain);\n // create internal render-to-texture tiles for the current scene.\n this._renderableTilesKeys = [];\n const keys = {};\n for (const tileID of transform.coveringTiles({\n tileSize: this.tileSize,\n minzoom: this.minzoom,\n maxzoom: this.maxzoom,\n reparseOverscaled: false,\n terrain\n })) {\n keys[tileID.key] = true;\n this._renderableTilesKeys.push(tileID.key);\n if (!this._tiles[tileID.key]) {\n tileID.posMatrix = new Float64Array(16) as any;\n mat4.ortho(tileID.posMatrix, 0, EXTENT, 0, EXTENT, 0, 1);\n this._tiles[tileID.key] = new Tile(tileID, this.tileSize);\n }\n }\n // free unused tiles\n for (const key in this._tiles) {\n if (!keys[key]) delete this._tiles[key];\n }\n }\n\n /**\n * Free render to texture cache\n * @param tileID - optional, free only corresponding to tileID.\n */\n freeRtt(tileID?: OverscaledTileID) {\n for (const key in this._tiles) {\n const tile = this._tiles[key];\n if (!tileID || tile.tileID.equals(tileID) || tile.tileID.isChildOf(tileID) || tileID.isChildOf(tile.tileID))\n tile.rtt = [];\n }\n }\n\n /**\n * get a list of tiles, which are loaded and should be rendered in the current scene\n * @returns the renderable tiles\n */\n getRenderableTiles(): Array {\n return this._renderableTilesKeys.map(key => this.getTileByID(key));\n }\n\n /**\n * get terrain tile by the TileID key\n * @param id - the tile id\n * @returns the tile\n */\n getTileByID(id: string): Tile {\n return this._tiles[id];\n }\n\n /**\n * Searches for the corresponding current renderable terrain-tiles\n * @param tileID - the tile to look for\n * @returns the tiles that were found\n */\n getTerrainCoords(tileID: OverscaledTileID): Record {\n const coords = {};\n for (const key of this._renderableTilesKeys) {\n const _tileID = this._tiles[key].tileID;\n if (_tileID.canonical.equals(tileID.canonical)) {\n const coord = tileID.clone();\n coord.posMatrix = new Float64Array(16) as any;\n mat4.ortho(coord.posMatrix, 0, EXTENT, 0, EXTENT, 0, 1);\n coords[key] = coord;\n } else if (_tileID.canonical.isChildOf(tileID.canonical)) {\n const coord = tileID.clone();\n coord.posMatrix = new Float64Array(16) as any;\n const dz = _tileID.canonical.z - tileID.canonical.z;\n const dx = _tileID.canonical.x - (_tileID.canonical.x >> dz << dz);\n const dy = _tileID.canonical.y - (_tileID.canonical.y >> dz << dz);\n const size = EXTENT >> dz;\n mat4.ortho(coord.posMatrix, 0, size, 0, size, 0, 1);\n mat4.translate(coord.posMatrix, coord.posMatrix, [-dx * size, -dy * size, 0]);\n coords[key] = coord;\n } else if (tileID.canonical.isChildOf(_tileID.canonical)) {\n const coord = tileID.clone();\n coord.posMatrix = new Float64Array(16) as any;\n const dz = tileID.canonical.z - _tileID.canonical.z;\n const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz);\n const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);\n const size = EXTENT >> dz;\n mat4.ortho(coord.posMatrix, 0, EXTENT, 0, EXTENT, 0, 1);\n mat4.translate(coord.posMatrix, coord.posMatrix, [dx * size, dy * size, 0]);\n mat4.scale(coord.posMatrix, coord.posMatrix, [1 / (2 ** dz), 1 / (2 ** dz), 0]);\n coords[key] = coord;\n }\n }\n return coords;\n }\n\n /**\n * find the covering raster-dem tile\n * @param tileID - the tile to look for\n * @param searchForDEM - Optional parameter to search for (parent) sourcetiles with loaded dem.\n * @returns the tile\n */\n getSourceTile(tileID: OverscaledTileID, searchForDEM?: boolean): Tile {\n const source = this.sourceCache._source;\n let z = tileID.overscaledZ - this.deltaZoom;\n if (z > source.maxzoom) z = source.maxzoom;\n if (z < source.minzoom) return null;\n // cache for tileID to terrain-tileID\n if (!this._sourceTileCache[tileID.key])\n this._sourceTileCache[tileID.key] = tileID.scaledTo(z).key;\n let tile = this.sourceCache.getTileByID(this._sourceTileCache[tileID.key]);\n // during tile-loading phase look if parent tiles (with loaded dem) are available.\n if (!(tile && tile.dem) && searchForDEM)\n while (z >= source.minzoom && !(tile && tile.dem))\n tile = this.sourceCache.getTileByID(tileID.scaledTo(z--).key);\n return tile;\n }\n\n /**\n * get a list of tiles, loaded after a specific time. This is used to update depth & coords framebuffers.\n * @param time - the time\n * @returns the relevant tiles\n */\n tilesAfterTime(time = Date.now()): Array {\n return Object.values(this._tiles).filter(t => t.timeAdded >= time);\n }\n}\n","\nimport {Tile} from '../source/tile';\nimport {mat4, vec2} from 'gl-matrix';\nimport {OverscaledTileID} from '../source/tile_id';\nimport {RGBAImage} from '../util/image';\nimport {warnOnce} from '../util/util';\nimport {Pos3dArray, TriangleIndexArray} from '../data/array_types.g';\nimport pos3dAttributes from '../data/pos3d_attributes';\nimport {SegmentVector} from '../data/segment';\nimport {Painter} from './painter';\nimport {Texture} from '../render/texture';\nimport type {Framebuffer} from '../gl/framebuffer';\nimport Point from '@mapbox/point-geometry';\nimport {MercatorCoordinate} from '../geo/mercator_coordinate';\nimport {TerrainSourceCache} from '../source/terrain_source_cache';\nimport {SourceCache} from '../source/source_cache';\nimport {EXTENT} from '../data/extent';\nimport type {TerrainSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {LngLat, earthRadius} from '../geo/lng_lat';\nimport {Mesh} from './mesh';\nimport {isInBoundsForZoomLngLat} from '../util/world_bounds';\n\n/**\n * @internal\n * A terrain GPU related object\n */\nexport type TerrainData = {\n 'u_depth': number;\n 'u_terrain': number;\n 'u_terrain_dim': number;\n 'u_terrain_matrix': mat4;\n 'u_terrain_unpack': number[];\n 'u_terrain_exaggeration': number;\n texture: WebGLTexture;\n depthTexture: WebGLTexture;\n tile: Tile;\n}\n\n/**\n * @internal\n * This is the main class which handles most of the 3D Terrain logic. It has the following topics:\n *\n * 1. loads raster-dem tiles via the internal sourceCache this.sourceCache\n * 2. creates a depth-framebuffer, which is used to calculate the visibility of coordinates\n * 3. creates a coords-framebuffer, which is used the get to tile-coordinate for a screen-pixel\n * 4. stores all render-to-texture tiles in the this.sourceCache._tiles\n * 5. calculates the elevation for a specific tile-coordinate\n * 6. creates a terrain-mesh\n *\n * A note about the GPU resource-usage:\n *\n * Framebuffers:\n *\n * - one for the depth & coords framebuffer with the size of the map-div.\n * - one for rendering a tile to texture with the size of tileSize (= 512x512).\n *\n * Textures:\n *\n * - one texture for an empty raster-dem tile with size 1x1\n * - one texture for an empty depth-buffer, when terrain is disabled with size 1x1\n * - one texture for an each loaded raster-dem with size of the source.tileSize\n * - one texture for the coords-framebuffer with the size of the map-div.\n * - one texture for the depth-framebuffer with the size of the map-div.\n * - one texture for the encoded tile-coords with the size 2*tileSize (=1024x1024)\n * - finally for each render-to-texture tile (= this._tiles) a set of textures\n * for each render stack (The stack-concept is documented in painter.ts).\n *\n * Normally there exists 1-3 Textures per tile, depending on the stylesheet.\n * Each Textures has the size 2*tileSize (= 1024x1024). Also there exists a\n * cache of the last 150 newest rendered tiles.\n *\n */\nexport class Terrain {\n /**\n * The style this terrain corresponds to\n */\n painter: Painter;\n /**\n * the sourcecache this terrain is based on\n */\n sourceCache: TerrainSourceCache;\n /**\n * the TerrainSpecification object passed to this instance\n */\n options: TerrainSpecification;\n /**\n * define the meshSize per tile.\n */\n meshSize: number;\n /**\n * multiplicator for the elevation. Used to make terrain more \"extreme\".\n */\n exaggeration: number;\n /**\n * to not see pixels in the render-to-texture tiles it is good to render them bigger\n * this number is the multiplicator (must be a power of 2) for the current tileSize.\n * So to get good results with not too much memory footprint a value of 2 should be fine.\n */\n qualityFactor: number;\n /**\n * holds the framebuffer object in size of the screen to render the coords & depth into a texture.\n */\n _fbo: Framebuffer;\n _fboCoordsTexture: Texture;\n _fboDepthTexture: Texture;\n _emptyDepthTexture: Texture;\n /**\n * GL Objects for the terrain-mesh\n * The mesh is a regular mesh, which has the advantage that it can be reused for all tiles.\n */\n _mesh: Mesh;\n /**\n * coords index contains a list of tileID.keys. This index is used to identify\n * the tile via the alpha-cannel in the coords-texture.\n * As the alpha-channel has 1 Byte a max of 255 tiles can rendered without an error.\n */\n coordsIndex: Array;\n /**\n * tile-coords encoded in the rgb channel, _coordsIndex is in the alpha-channel.\n */\n _coordsTexture: Texture;\n /**\n * accuracy of the coords. 2 * tileSize should be enough.\n */\n _coordsTextureSize: number;\n /**\n * variables for an empty dem texture, which is used while the raster-dem tile is loading.\n */\n _emptyDemUnpack: number[];\n _emptyDemTexture: Texture;\n _emptyDemMatrix: mat4;\n /**\n * as of overzooming of raster-dem tiles in high zoomlevels, this cache contains\n * matrices to transform from vector-tile coords to raster-dem-tile coords.\n */\n _demMatrixCache: {[_: string]: { matrix: mat4; coord: OverscaledTileID }};\n\n constructor(painter: Painter, sourceCache: SourceCache, options: TerrainSpecification) {\n this.painter = painter;\n this.sourceCache = new TerrainSourceCache(sourceCache);\n this.options = options;\n this.exaggeration = typeof options.exaggeration === 'number' ? options.exaggeration : 1.0;\n this.qualityFactor = 2;\n this.meshSize = 128;\n this._demMatrixCache = {};\n this.coordsIndex = [];\n this._coordsTextureSize = 1024;\n }\n\n /**\n * get the elevation-value from original dem-data for a given tile-coordinate\n * @param tileID - the tile to get elevation for\n * @param x - between 0 .. EXTENT\n * @param y - between 0 .. EXTENT\n * @param extent - optional, default 8192\n * @returns the elevation\n */\n getDEMElevation(tileID: OverscaledTileID, x: number, y: number, extent: number = EXTENT): number {\n if (!(x >= 0 && x < extent && y >= 0 && y < extent)) return 0;\n const terrain = this.getTerrainData(tileID);\n const dem = terrain.tile?.dem;\n if (!dem)\n return 0;\n\n const pos = vec2.transformMat4([] as any, [x / extent * EXTENT, y / extent * EXTENT], terrain.u_terrain_matrix);\n const coord = [pos[0] * dem.dim, pos[1] * dem.dim];\n\n // bilinear interpolation\n const cx = Math.floor(coord[0]),\n cy = Math.floor(coord[1]),\n tx = coord[0] - cx,\n ty = coord[1] - cy;\n return (\n dem.get(cx, cy) * (1 - tx) * (1 - ty) +\n dem.get(cx + 1, cy) * (tx) * (1 - ty) +\n dem.get(cx, cy + 1) * (1 - tx) * (ty) +\n dem.get(cx + 1, cy + 1) * (tx) * (ty)\n );\n }\n\n /**\n * Get the elevation for given {@link LngLat} in respect of exaggeration.\n * @param lnglat - the location\n * @param zoom - the zoom\n * @returns the elevation\n */\n getElevationForLngLatZoom(lnglat: LngLat, zoom: number) {\n if (!isInBoundsForZoomLngLat(zoom, lnglat.wrap())) return 0;\n const {tileID, mercatorX, mercatorY} = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom);\n return this.getElevation(tileID, mercatorX % EXTENT, mercatorY % EXTENT, EXTENT);\n }\n\n /**\n * Get the elevation for given coordinate in respect of exaggeration.\n * @param tileID - the tile id\n * @param x - between 0 .. EXTENT\n * @param y - between 0 .. EXTENT\n * @param extent - optional, default 8192\n * @returns the elevation\n */\n getElevation(tileID: OverscaledTileID, x: number, y: number, extent: number = EXTENT): number {\n return this.getDEMElevation(tileID, x, y, extent) * this.exaggeration;\n }\n\n /**\n * returns a Terrain Object for a tile. Unless the tile corresponds to data (e.g. tile is loading), return a flat dem object\n * @param tileID - the tile to get the terrain for\n * @returns the terrain data to use in the program\n */\n getTerrainData(tileID: OverscaledTileID): TerrainData {\n // create empty DEM Objects, which will used while raster-dem tiles are loading.\n // creates an empty depth-buffer texture which is needed, during the initialization process of the 3d mesh..\n if (!this._emptyDemTexture) {\n const context = this.painter.context;\n const image = new RGBAImage({width: 1, height: 1}, new Uint8Array(1 * 4));\n this._emptyDepthTexture = new Texture(context, image, context.gl.RGBA, {premultiply: false});\n this._emptyDemUnpack = [0, 0, 0, 0];\n this._emptyDemTexture = new Texture(context, new RGBAImage({width: 1, height: 1}), context.gl.RGBA, {premultiply: false});\n this._emptyDemTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);\n this._emptyDemMatrix = mat4.identity([] as any);\n }\n // find covering dem tile and prepare demTexture\n const sourceTile = this.sourceCache.getSourceTile(tileID, true);\n if (sourceTile && sourceTile.dem && (!sourceTile.demTexture || sourceTile.needsTerrainPrepare)) {\n const context = this.painter.context;\n sourceTile.demTexture = this.painter.getTileTexture(sourceTile.dem.stride);\n if (sourceTile.demTexture) sourceTile.demTexture.update(sourceTile.dem.getPixels(), {premultiply: false});\n else sourceTile.demTexture = new Texture(context, sourceTile.dem.getPixels(), context.gl.RGBA, {premultiply: false});\n sourceTile.demTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);\n sourceTile.needsTerrainPrepare = false;\n }\n // create matrix for lookup in dem data\n const matrixKey = sourceTile && (sourceTile + sourceTile.tileID.key) + tileID.key;\n if (matrixKey && !this._demMatrixCache[matrixKey]) {\n const maxzoom = this.sourceCache.sourceCache._source.maxzoom;\n let dz = tileID.canonical.z - sourceTile.tileID.canonical.z;\n if (tileID.overscaledZ > tileID.canonical.z) {\n if (tileID.canonical.z >= maxzoom) dz = tileID.canonical.z - maxzoom;\n else warnOnce('cannot calculate elevation if elevation maxzoom > source.maxzoom');\n }\n const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz);\n const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);\n const demMatrix = mat4.fromScaling(new Float64Array(16) as any, [1 / (EXTENT << dz), 1 / (EXTENT << dz), 0]);\n mat4.translate(demMatrix, demMatrix, [dx * EXTENT, dy * EXTENT, 0]);\n this._demMatrixCache[tileID.key] = {matrix: demMatrix, coord: tileID};\n }\n // return uniform values & textures\n return {\n 'u_depth': 2,\n 'u_terrain': 3,\n 'u_terrain_dim': sourceTile && sourceTile.dem && sourceTile.dem.dim || 1,\n 'u_terrain_matrix': matrixKey ? this._demMatrixCache[tileID.key].matrix : this._emptyDemMatrix,\n 'u_terrain_unpack': sourceTile && sourceTile.dem && sourceTile.dem.getUnpackVector() || this._emptyDemUnpack,\n 'u_terrain_exaggeration': this.exaggeration,\n texture: (sourceTile && sourceTile.demTexture || this._emptyDemTexture).texture,\n depthTexture: (this._fboDepthTexture || this._emptyDepthTexture).texture,\n tile: sourceTile\n };\n }\n\n /**\n * get a framebuffer as big as the map-div, which will be used to render depth & coords into a texture\n * @param texture - the texture\n * @returns the frame buffer\n */\n getFramebuffer(texture: string): Framebuffer {\n const painter = this.painter;\n const width = painter.width / devicePixelRatio;\n const height = painter.height / devicePixelRatio;\n if (this._fbo && (this._fbo.width !== width || this._fbo.height !== height)) {\n this._fbo.destroy();\n this._fboCoordsTexture.destroy();\n this._fboDepthTexture.destroy();\n delete this._fbo;\n delete this._fboDepthTexture;\n delete this._fboCoordsTexture;\n }\n if (!this._fboCoordsTexture) {\n this._fboCoordsTexture = new Texture(painter.context, {width, height, data: null}, painter.context.gl.RGBA, {premultiply: false});\n this._fboCoordsTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE);\n }\n if (!this._fboDepthTexture) {\n this._fboDepthTexture = new Texture(painter.context, {width, height, data: null}, painter.context.gl.RGBA, {premultiply: false});\n this._fboDepthTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE);\n }\n if (!this._fbo) {\n this._fbo = painter.context.createFramebuffer(width, height, true, false);\n this._fbo.depthAttachment.set(painter.context.createRenderbuffer(painter.context.gl.DEPTH_COMPONENT16, width, height));\n }\n this._fbo.colorAttachment.set(texture === 'coords' ? this._fboCoordsTexture.texture : this._fboDepthTexture.texture);\n return this._fbo;\n }\n\n /**\n * create coords texture, needed to grab coordinates from canvas\n * encode coords coordinate into 4 bytes:\n * - 8 lower bits for x\n * - 8 lower bits for y\n * - 4 higher bits for x\n * - 4 higher bits for y\n * - 8 bits for coordsIndex (1 .. 255) (= number of terraintile), is later setted in draw_terrain uniform value\n * @returns the texture\n */\n getCoordsTexture(): Texture {\n const context = this.painter.context;\n if (this._coordsTexture) return this._coordsTexture;\n const data = new Uint8Array(this._coordsTextureSize * this._coordsTextureSize * 4);\n for (let y = 0, i = 0; y < this._coordsTextureSize; y++) for (let x = 0; x < this._coordsTextureSize; x++, i += 4) {\n data[i + 0] = x & 255;\n data[i + 1] = y & 255;\n data[i + 2] = ((x >> 8) << 4) | (y >> 8);\n data[i + 3] = 0;\n }\n const image = new RGBAImage({width: this._coordsTextureSize, height: this._coordsTextureSize}, new Uint8Array(data.buffer));\n const texture = new Texture(context, image, context.gl.RGBA, {premultiply: false});\n texture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);\n this._coordsTexture = texture;\n return texture;\n }\n\n /**\n * Reads a pixel from the coords-framebuffer and translate this to mercator.\n * @param p - Screen-Coordinate\n * @returns mercator coordinate for a screen pixel\n */\n pointCoordinate(p: Point): MercatorCoordinate {\n // First, ensure the coords framebuffer is up to date.\n this.painter.maybeDrawDepthAndCoords(true);\n\n const rgba = new Uint8Array(4);\n const context = this.painter.context, gl = context.gl;\n const px = Math.round(p.x * this.painter.pixelRatio / devicePixelRatio);\n const py = Math.round(p.y * this.painter.pixelRatio / devicePixelRatio);\n const fbHeight = Math.round(this.painter.height / devicePixelRatio);\n // grab coordinate pixel from coordinates framebuffer\n context.bindFramebuffer.set(this.getFramebuffer('coords').framebuffer);\n gl.readPixels(px, fbHeight - py - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba);\n context.bindFramebuffer.set(null);\n // decode coordinates (encoding see getCoordsTexture)\n const x = rgba[0] + ((rgba[2] >> 4) << 8);\n const y = rgba[1] + ((rgba[2] & 15) << 8);\n const tileID = this.coordsIndex[255 - rgba[3]];\n const tile = tileID && this.sourceCache.getTileByID(tileID);\n if (!tile) return null;\n const coordsSize = this._coordsTextureSize;\n const worldSize = (1 << tile.tileID.canonical.z) * coordsSize;\n return new MercatorCoordinate(\n (tile.tileID.canonical.x * coordsSize + x) / worldSize + tile.tileID.wrap,\n (tile.tileID.canonical.y * coordsSize + y) / worldSize,\n this.getElevation(tile.tileID, x, y, coordsSize)\n );\n }\n\n /**\n * Reads the depth value from the depth-framebuffer at a given screen pixel\n * @param p - Screen coordinate\n * @returns depth value in clip space (between 0 and 1)\n */\n\n depthAtPoint(p: Point): number {\n const rgba = new Uint8Array(4);\n const context = this.painter.context, gl = context.gl;\n context.bindFramebuffer.set(this.getFramebuffer('depth').framebuffer);\n gl.readPixels(p.x, this.painter.height / devicePixelRatio - p.y - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba);\n context.bindFramebuffer.set(null);\n // decode coordinates (encoding see terran_depth.fragment.glsl)\n const depthValue = (rgba[0] / (256 * 256 * 256) + rgba[1] / (256 * 256) + rgba[2] / 256 + rgba[3]) / 256;\n return depthValue;\n }\n\n /**\n * create a regular mesh which will be used by all terrain-tiles\n * @returns the created regular mesh\n */\n getTerrainMesh(): Mesh {\n if (this._mesh) return this._mesh;\n const context = this.painter.context;\n const vertexArray = new Pos3dArray();\n const indexArray = new TriangleIndexArray();\n const meshSize = this.meshSize;\n const delta = EXTENT / meshSize;\n const meshSize2 = meshSize * meshSize;\n for (let y = 0; y <= meshSize; y++) for (let x = 0; x <= meshSize; x++)\n vertexArray.emplaceBack(x * delta, y * delta, 0);\n for (let y = 0; y < meshSize2; y += meshSize + 1) for (let x = 0; x < meshSize; x++) {\n indexArray.emplaceBack(x + y, meshSize + x + y + 1, meshSize + x + y + 2);\n indexArray.emplaceBack(x + y, meshSize + x + y + 2, x + y + 1);\n }\n // add an extra frame around the mesh to avoid stiching on tile boundaries with different zoomlevels\n // first code-block is for top-bottom frame and second for left-right frame\n const offsetTop = vertexArray.length, offsetBottom = offsetTop + (meshSize + 1) * 2;\n for (const y of [0, 1]) for (let x = 0; x <= meshSize; x++) for (const z of [0, 1])\n vertexArray.emplaceBack(x * delta, y * EXTENT, z);\n for (let x = 0; x < meshSize * 2; x += 2) {\n indexArray.emplaceBack(offsetBottom + x, offsetBottom + x + 1, offsetBottom + x + 3);\n indexArray.emplaceBack(offsetBottom + x, offsetBottom + x + 3, offsetBottom + x + 2);\n indexArray.emplaceBack(offsetTop + x, offsetTop + x + 3, offsetTop + x + 1);\n indexArray.emplaceBack(offsetTop + x, offsetTop + x + 2, offsetTop + x + 3);\n }\n const offsetLeft = vertexArray.length, offsetRight = offsetLeft + (meshSize + 1) * 2;\n for (const x of [0, 1]) for (let y = 0; y <= meshSize; y++) for (const z of [0, 1])\n vertexArray.emplaceBack(x * EXTENT, y * delta, z);\n for (let y = 0; y < meshSize * 2; y += 2) {\n indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 1, offsetLeft + y + 3);\n indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 3, offsetLeft + y + 2);\n indexArray.emplaceBack(offsetRight + y, offsetRight + y + 3, offsetRight + y + 1);\n indexArray.emplaceBack(offsetRight + y, offsetRight + y + 2, offsetRight + y + 3);\n }\n this._mesh = new Mesh(\n context.createVertexBuffer(vertexArray, pos3dAttributes.members),\n context.createIndexBuffer(indexArray),\n SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length)\n );\n return this._mesh;\n }\n\n /**\n * Calculates a height of the frame around the terrain-mesh to avoid stiching between\n * tile boundaries in different zoomlevels.\n * @param zoom - current zoomlevel\n * @returns the elevation delta in meters\n */\n getMeshFrameDelta(zoom: number): number {\n // divide by 5 is evaluated by trial & error to get a frame in the right height\n return 2 * Math.PI * earthRadius / Math.pow(2, zoom) / 5;\n }\n\n getMinTileElevationForLngLatZoom(lnglat: LngLat, zoom: number) {\n const {tileID} = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom);\n return this.getMinMaxElevation(tileID).minElevation ?? 0;\n }\n\n /**\n * Get the minimum and maximum elevation contained in a tile. This includes any\n * exaggeration included in the terrain.\n *\n * @param tileID - ID of the tile to be used as a source for the min/max elevation\n * @returns the minimum and maximum elevation found in the tile, including the terrain's\n * exaggeration\n */\n getMinMaxElevation(tileID: OverscaledTileID): {minElevation: number | null; maxElevation: number | null} {\n const tile = this.getTerrainData(tileID).tile;\n const minMax = {minElevation: null, maxElevation: null};\n if (tile && tile.dem) {\n minMax.minElevation = tile.dem.min * this.exaggeration;\n minMax.maxElevation = tile.dem.max * this.exaggeration;\n }\n return minMax;\n }\n\n _getOverscaledTileIDFromLngLatZoom(lnglat: LngLat, zoom: number): { tileID: OverscaledTileID; mercatorX: number; mercatorY: number} {\n const mercatorCoordinate = MercatorCoordinate.fromLngLat(lnglat.wrap());\n const worldSize = (1 << zoom) * EXTENT;\n const mercatorX = mercatorCoordinate.x * worldSize;\n const mercatorY = mercatorCoordinate.y * worldSize;\n const tileX = Math.floor(mercatorX / EXTENT), tileY = Math.floor(mercatorY / EXTENT);\n const tileID = new OverscaledTileID(zoom, 0, zoom, tileX, tileY);\n return {\n tileID,\n mercatorX,\n mercatorY\n };\n }\n}\n","import {Texture} from '../render/texture';\nimport {Context} from './context';\nimport {Framebuffer} from './framebuffer';\n\nexport type PoolObject = {\n id: number;\n fbo: Framebuffer;\n texture: Texture;\n stamp: number;\n inUse: boolean;\n};\n/**\n * @internal\n * `RenderPool` is a resource pool for textures and framebuffers\n */\nexport class RenderPool {\n private _objects: Array;\n /**\n * An index array of recently used pool objects.\n * Items that are used recently are last in the array\n */\n private _recentlyUsed: Array;\n private _stamp: number;\n\n constructor(\n private readonly _context: Context,\n private readonly _size: number,\n private readonly _tileSize: number) {\n this._objects = [];\n this._recentlyUsed = [];\n this._stamp = 0;\n }\n\n public destruct() {\n for (const obj of this._objects) {\n obj.texture.destroy();\n obj.fbo.destroy();\n }\n }\n\n private _createObject(id: number): PoolObject {\n const fbo = this._context.createFramebuffer(this._tileSize, this._tileSize, true, true);\n const texture = new Texture(this._context, {width: this._tileSize, height: this._tileSize, data: null}, this._context.gl.RGBA);\n texture.bind(this._context.gl.LINEAR, this._context.gl.CLAMP_TO_EDGE);\n fbo.depthAttachment.set(this._context.createRenderbuffer(this._context.gl.DEPTH_STENCIL, this._tileSize, this._tileSize));\n fbo.colorAttachment.set(texture.texture);\n return {id, fbo, texture, stamp: -1, inUse: false};\n }\n\n public getObjectForId(id: number): PoolObject {\n return this._objects[id];\n }\n\n public useObject(obj: PoolObject) {\n obj.inUse = true;\n this._recentlyUsed = this._recentlyUsed.filter(id => obj.id !== id);\n this._recentlyUsed.push(obj.id);\n }\n\n public stampObject(obj: PoolObject) {\n obj.stamp = ++this._stamp;\n }\n\n public getOrCreateFreeObject(): PoolObject {\n // check for free existing object\n for (const id of this._recentlyUsed) {\n if (!this._objects[id].inUse)\n return this._objects[id];\n }\n if (this._objects.length >= this._size)\n throw new Error('No free RenderPool available, call freeAllObjects() required!');\n // create new object\n const obj = this._createObject(this._objects.length);\n this._objects.push(obj);\n return obj;\n }\n\n public freeObject(obj: PoolObject) {\n obj.inUse = false;\n }\n\n public freeAllObjects() {\n for (const obj of this._objects)\n this.freeObject(obj);\n }\n\n public isFull(): boolean {\n if (this._objects.length < this._size) {\n return false;\n }\n return this._objects.some(o => !o.inUse) === false;\n }\n}\n","import {Painter} from './painter';\nimport {Tile} from '../source/tile';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {OverscaledTileID} from '../source/tile_id';\nimport {drawTerrain} from './draw_terrain';\nimport {Style} from '../style/style';\nimport {Terrain} from './terrain';\nimport {RenderPool} from '../gl/render_pool';\nimport {Texture} from './texture';\nimport type {StyleLayer} from '../style/style_layer';\n\n/**\n * lookup table which layers should rendered to texture\n */\nconst LAYERS: { [keyof in StyleLayer['type']]?: boolean } = {\n background: true,\n fill: true,\n line: true,\n raster: true,\n hillshade: true\n};\n\n/**\n * @internal\n * A helper class to help define what should be rendered to texture and how\n */\nexport class RenderToTexture {\n painter: Painter;\n terrain: Terrain;\n pool: RenderPool;\n /**\n * coordsDescendingInv contains a list of all tiles which should be rendered for one render-to-texture tile\n * e.g. render 4 raster-tiles with size 256px to the 512px render-to-texture tile\n */\n _coordsDescendingInv: {[_: string]: {[_:string]: Array}};\n /**\n * create a string representation of all to tiles rendered to render-to-texture tiles\n * this string representation is used to check if tile should be re-rendered.\n */\n _coordsDescendingInvStr: {[_: string]: {[_:string]: string}};\n /**\n * store for render-stacks\n * a render stack is a set of layers which should be rendered into one texture\n * every stylesheet can have multiple stacks. A new stack is created if layers which should\n * not rendered to texture sit between layers which should rendered to texture. e.g. hillshading or symbols\n */\n _stacks: Array>;\n /**\n * remember the previous processed layer to check if a new stack is needed\n */\n _prevType: string;\n /**\n * a list of tiles that can potentially rendered\n */\n _renderableTiles: Array;\n /**\n * a list of tiles that should be rendered to screen in the next render-call\n */\n _rttTiles: Array;\n /**\n * a list of all layer-ids which should be rendered\n */\n _renderableLayerIds: Array;\n\n constructor(painter: Painter, terrain: Terrain) {\n this.painter = painter;\n this.terrain = terrain;\n this.pool = new RenderPool(painter.context, 30, terrain.sourceCache.tileSize * terrain.qualityFactor);\n }\n\n destruct() {\n this.pool.destruct();\n }\n\n getTexture(tile: Tile): Texture {\n return this.pool.getObjectForId(tile.rtt[this._stacks.length - 1].id).texture;\n }\n\n prepareForRender(style: Style, zoom: number) {\n this._stacks = [];\n this._prevType = null;\n this._rttTiles = [];\n this._renderableTiles = this.terrain.sourceCache.getRenderableTiles();\n this._renderableLayerIds = style._order.filter(id => !style._layers[id].isHidden(zoom));\n\n this._coordsDescendingInv = {};\n for (const id in style.sourceCaches) {\n this._coordsDescendingInv[id] = {};\n const tileIDs = style.sourceCaches[id].getVisibleCoordinates();\n for (const tileID of tileIDs) {\n const keys = this.terrain.sourceCache.getTerrainCoords(tileID);\n for (const key in keys) {\n if (!this._coordsDescendingInv[id][key]) this._coordsDescendingInv[id][key] = [];\n this._coordsDescendingInv[id][key].push(keys[key]);\n }\n }\n }\n\n this._coordsDescendingInvStr = {};\n for (const id of style._order) {\n const layer = style._layers[id], source = layer.source;\n if (LAYERS[layer.type]) {\n if (!this._coordsDescendingInvStr[source]) {\n this._coordsDescendingInvStr[source] = {};\n for (const key in this._coordsDescendingInv[source])\n this._coordsDescendingInvStr[source][key] = this._coordsDescendingInv[source][key].map(c => c.key).sort().join();\n }\n }\n }\n\n // check tiles to render\n for (const tile of this._renderableTiles) {\n for (const source in this._coordsDescendingInvStr) {\n // rerender if there are more coords to render than in the last rendering\n const coords = this._coordsDescendingInvStr[source][tile.tileID.key];\n if (coords && coords !== tile.rttCoords[source]) tile.rtt = [];\n }\n }\n }\n\n /**\n * due that switching textures is relatively slow, the render\n * layer-by-layer context is not practicable. To bypass this problem\n * this lines of code stack all layers and later render all at once.\n * Because of the stylesheet possibility to mixing render-to-texture layers\n * and 'live'-layers (f.e. symbols) it is necessary to create more stacks. For example\n * a symbol-layer is in between of fill-layers.\n * @param layer - the layer to render\n * @returns if true layer is rendered to texture, otherwise false\n */\n renderLayer(layer: StyleLayer): boolean {\n if (layer.isHidden(this.painter.transform.zoom)) return false;\n\n const type = layer.type;\n const painter = this.painter;\n const isLastLayer = this._renderableLayerIds[this._renderableLayerIds.length - 1] === layer.id;\n\n // remember background, fill, line & raster layer to render into a stack\n if (LAYERS[type]) {\n // create a new stack if previous layer was not rendered to texture (f.e. symbols)\n if (!this._prevType || !LAYERS[this._prevType]) this._stacks.push([]);\n // push current render-to-texture layer to render-stack\n this._prevType = type;\n this._stacks[this._stacks.length - 1].push(layer.id);\n // rendering is done later, all in once\n if (!isLastLayer) return true;\n }\n\n // in case a stack is finished render all collected stack-layers into a texture\n if (LAYERS[this._prevType] || (LAYERS[type] && isLastLayer)) {\n this._prevType = type;\n const stack = this._stacks.length - 1, layers = this._stacks[stack] || [];\n for (const tile of this._renderableTiles) {\n // if render pool is full draw current tiles to screen and free pool\n if (this.pool.isFull()) {\n drawTerrain(this.painter, this.terrain, this._rttTiles);\n this._rttTiles = [];\n this.pool.freeAllObjects();\n }\n this._rttTiles.push(tile);\n // check for cached PoolObject\n if (tile.rtt[stack]) {\n const obj = this.pool.getObjectForId(tile.rtt[stack].id);\n if (obj.stamp === tile.rtt[stack].stamp) {\n this.pool.useObject(obj);\n continue;\n }\n }\n // get free PoolObject\n const obj = this.pool.getOrCreateFreeObject();\n this.pool.useObject(obj);\n this.pool.stampObject(obj);\n tile.rtt[stack] = {id: obj.id, stamp: obj.stamp};\n // prepare PoolObject for rendering\n painter.context.bindFramebuffer.set(obj.fbo.framebuffer);\n painter.context.clear({color: Color.transparent, stencil: 0});\n painter.currentStencilSource = undefined;\n for (let l = 0; l < layers.length; l++) {\n const layer = painter.style._layers[layers[l]];\n const coords = layer.source ? this._coordsDescendingInv[layer.source][tile.tileID.key] : [tile.tileID];\n painter.context.viewport.set([0, 0, obj.fbo.width, obj.fbo.height]);\n painter._renderTileClippingMasks(layer, coords);\n painter.renderLayer(painter, painter.style.sourceCaches[layer.source], layer, coords);\n if (layer.source) tile.rttCoords[layer.source] = this._coordsDescendingInvStr[layer.source][tile.tileID.key];\n }\n }\n drawTerrain(this.painter, this.terrain, this._rttTiles);\n this._rttTiles = [];\n this.pool.freeAllObjects();\n\n return LAYERS[type];\n }\n\n return false;\n }\n\n}\n","export const defaultLocale = {\n 'AttributionControl.ToggleAttribution': 'Toggle attribution',\n 'AttributionControl.MapFeedback': 'Map feedback',\n 'FullscreenControl.Enter': 'Enter fullscreen',\n 'FullscreenControl.Exit': 'Exit fullscreen',\n 'GeolocateControl.FindMyLocation': 'Find my location',\n 'GeolocateControl.LocationNotAvailable': 'Location not available',\n 'LogoControl.Title': 'MapLibre logo',\n 'Map.Title': 'Map',\n 'Marker.Title': 'Map marker',\n 'NavigationControl.ResetBearing': 'Reset bearing to north',\n 'NavigationControl.ZoomIn': 'Zoom in',\n 'NavigationControl.ZoomOut': 'Zoom out',\n 'Popup.Close': 'Close popup',\n 'ScaleControl.Feet': 'ft',\n 'ScaleControl.Meters': 'm',\n 'ScaleControl.Kilometers': 'km',\n 'ScaleControl.Miles': 'mi',\n 'ScaleControl.NauticalMiles': 'nm',\n 'TerrainControl.Enable': 'Enable terrain',\n 'TerrainControl.Disable': 'Disable terrain',\n 'CooperativeGesturesHandler.WindowsHelpText': 'Use Ctrl + scroll to zoom the map',\n 'CooperativeGesturesHandler.MacHelpText': 'Use ⌘ + scroll to zoom the map',\n 'CooperativeGesturesHandler.MobileHelpText': 'Use two fingers to move the map',\n};\n","import {extend, warnOnce, uniqueId, isImageBitmap, Complete} from '../util/util';\nimport {browser} from '../util/browser';\nimport {DOM} from '../util/dom';\nimport packageJSON from '../../package.json' with {type: 'json'};\nimport {GetResourceResponse, getJSON} from '../util/ajax';\nimport {ImageRequest} from '../util/image_request';\nimport {RequestManager, ResourceType} from '../util/request_manager';\nimport {Style, StyleSwapOptions} from '../style/style';\nimport {EvaluationParameters} from '../style/evaluation_parameters';\nimport {Painter} from '../render/painter';\nimport {Transform} from '../geo/transform';\nimport {Hash} from './hash';\nimport {HandlerManager} from './handler_manager';\nimport {Camera, CameraOptions, CameraUpdateTransformFunction, FitBoundsOptions} from './camera';\nimport {LngLat} from '../geo/lng_lat';\nimport {LngLatBounds} from '../geo/lng_lat_bounds';\nimport Point from '@mapbox/point-geometry';\nimport {AttributionControl, AttributionControlOptions, defaultAttributionControlOptions} from './control/attribution_control';\nimport {LogoControl} from './control/logo_control';\nimport {RGBAImage} from '../util/image';\nimport {Event, ErrorEvent, Listener} from '../util/evented';\nimport {MapEventType, MapLayerEventType, MapMouseEvent, MapSourceDataEvent, MapStyleDataEvent} from './events';\nimport {TaskQueue} from '../util/task_queue';\nimport {throttle} from '../util/throttle';\nimport {webpSupported} from '../util/webp_supported';\nimport {PerformanceMarkers, PerformanceUtils} from '../util/performance';\nimport {Source} from '../source/source';\nimport {StyleLayer} from '../style/style_layer';\nimport {Terrain} from '../render/terrain';\nimport {RenderToTexture} from '../render/render_to_texture';\nimport {config} from '../util/config';\nimport {defaultLocale} from './default_locale';\n\nimport type {RequestTransformFunction} from '../util/request_manager';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport type {LngLatBoundsLike} from '../geo/lng_lat_bounds';\nimport type {AddLayerObject, FeatureIdentifier, StyleOptions, StyleSetterOptions} from '../style/style';\nimport type {MapDataEvent} from './events';\nimport type {StyleImage, StyleImageInterface, StyleImageMetadata} from '../style/style_image';\nimport type {PointLike} from './camera';\nimport type {ScrollZoomHandler} from './handler/scroll_zoom';\nimport type {BoxZoomHandler} from './handler/box_zoom';\nimport type {AroundCenterOptions, TwoFingersTouchPitchHandler} from './handler/two_fingers_touch';\nimport type {DragRotateHandler} from './handler/shim/drag_rotate';\nimport type {DragPanHandler, DragPanOptions} from './handler/shim/drag_pan';\nimport type {CooperativeGesturesHandler, GestureOptions} from './handler/cooperative_gestures';\nimport type {KeyboardHandler} from './handler/keyboard';\nimport type {DoubleClickZoomHandler} from './handler/shim/dblclick_zoom';\nimport type {TwoFingersTouchZoomRotateHandler} from './handler/shim/two_fingers_touch';\nimport type {TaskID} from '../util/task_queue';\nimport type {\n FilterSpecification,\n StyleSpecification,\n LightSpecification,\n SourceSpecification,\n TerrainSpecification,\n SkySpecification\n} from '@maplibre/maplibre-gl-style-spec';\nimport type {CanvasSourceSpecification} from '../source/canvas_source';\nimport type {MapGeoJSONFeature} from '../util/vectortile_to_geojson';\nimport type {ControlPosition, IControl} from './control/control';\nimport type {QueryRenderedFeaturesOptions, QuerySourceFeatureOptions} from '../source/query_features';\n\nconst version = packageJSON.version;\n\n/**\n * The {@link Map} options object.\n */\nexport type MapOptions = {\n /**\n * If `true`, the map's position (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page's URL.\n * For example, `http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60`.\n * An additional string may optionally be provided to indicate a parameter-styled hash,\n * e.g. http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar, where foo\n * is a custom parameter and bar is an arbitrary hash distinct from the map hash.\n * @defaultValue false\n */\n hash?: boolean | string;\n /**\n * If `false`, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction.\n * @defaultValue true\n */\n interactive?: boolean;\n /**\n * The HTML element in which MapLibre GL JS will render the map, or the element's string `id`. The specified element must have no children.\n */\n container: HTMLElement | string;\n /**\n * The threshold, measured in degrees, that determines when the map's\n * bearing will snap to north. For example, with a `bearingSnap` of 7, if the user rotates\n * the map within 7 degrees of north, the map will automatically snap to exact north.\n * @defaultValue 7\n */\n bearingSnap?: number;\n /**\n * If set, an {@link AttributionControl} will be added to the map with the provided options.\n * To disable the attribution control, pass `false`.\n * Note: showing the logo of MapLibre is not required for using MapLibre.\n * @defaultValue compact: true, customAttribution: \"MapLibre ...\".\n */\n attributionControl?: false | AttributionControlOptions;\n /**\n * If `true`, the MapLibre logo will be shown.\n */\n maplibreLogo?: boolean;\n /**\n * A string representing the position of the MapLibre wordmark on the map. Valid options are `top-left`,`top-right`, `bottom-left`, or `bottom-right`.\n * @defaultValue 'bottom-left'\n */\n logoPosition?: ControlPosition;\n /**\n * If `true`, map creation will fail if the performance of MapLibre GL JS would be dramatically worse than expected\n * (i.e. a software renderer would be used).\n * @defaultValue false\n */\n failIfMajorPerformanceCaveat?: boolean;\n /**\n * If `true`, the map's canvas can be exported to a PNG using `map.getCanvas().toDataURL()`. This is `false` by default as a performance optimization.\n * @defaultValue false\n */\n preserveDrawingBuffer?: boolean;\n /**\n * If `true`, the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers.\n * Disabled by default as a performance optimization.\n */\n antialias?: boolean;\n /**\n * If `false`, the map won't attempt to re-request tiles once they expire per their HTTP `cacheControl`/`expires` headers.\n * @defaultValue true\n */\n refreshExpiredTiles?: boolean;\n /**\n * If set, the map will be constrained to the given bounds.\n */\n maxBounds?: LngLatBoundsLike;\n /**\n * If `true`, the \"scroll to zoom\" interaction is enabled. {@link AroundCenterOptions} are passed as options to {@link ScrollZoomHandler#enable}.\n * @defaultValue true\n */\n scrollZoom?: boolean | AroundCenterOptions;\n /**\n * The minimum zoom level of the map (0-24).\n * @defaultValue 0\n */\n minZoom?: number | null;\n /**\n * The maximum zoom level of the map (0-24).\n * @defaultValue 22\n */\n maxZoom?: number | null;\n /**\n * The minimum pitch of the map (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.\n * @defaultValue 0\n */\n minPitch?: number | null;\n /**\n * The maximum pitch of the map (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.\n * @defaultValue 60\n */\n maxPitch?: number | null;\n /**\n * If `true`, the \"box zoom\" interaction is enabled (see {@link BoxZoomHandler}).\n * @defaultValue true\n */\n boxZoom?: boolean;\n /**\n * If `true`, the \"drag to rotate\" interaction is enabled (see {@link DragRotateHandler}).\n * @defaultValue true\n */\n dragRotate?: boolean;\n /**\n * If `true`, the \"drag to pan\" interaction is enabled. An `Object` value is passed as options to {@link DragPanHandler#enable}.\n * @defaultValue true\n */\n dragPan?: boolean | DragPanOptions;\n /**\n * If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}).\n * @defaultValue true\n */\n keyboard?: boolean;\n /**\n * If `true`, the \"double click to zoom\" interaction is enabled (see {@link DoubleClickZoomHandler}).\n * @defaultValue true\n */\n doubleClickZoom?: boolean;\n /**\n * If `true`, the \"pinch to rotate and zoom\" interaction is enabled. An `Object` value is passed as options to {@link TwoFingersTouchZoomRotateHandler#enable}.\n * @defaultValue true\n */\n touchZoomRotate?: boolean | AroundCenterOptions;\n /**\n * If `true`, the \"drag to pitch\" interaction is enabled. An `Object` value is passed as options to {@link TwoFingersTouchPitchHandler#enable}.\n * @defaultValue true\n */\n touchPitch?: boolean | AroundCenterOptions;\n /**\n * If `true` or set to an options object, the map is only accessible on desktop while holding Command/Ctrl and only accessible on mobile with two fingers. Interacting with the map using normal gestures will trigger an informational screen. With this option enabled, \"drag to pitch\" requires a three-finger gesture. Cooperative gestures are disabled when a map enters fullscreen using {@link FullscreenControl}.\n * @defaultValue false\n */\n cooperativeGestures?: GestureOptions;\n /**\n * If `true`, the map will automatically resize when the browser window resizes.\n * @defaultValue true\n */\n trackResize?: boolean;\n /**\n * The initial geographical centerpoint of the map. If `center` is not specified in the constructor options, MapLibre GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `[0, 0]` Note: MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.\n * @defaultValue [0, 0]\n */\n center?: LngLatLike;\n /**\n * The initial zoom level of the map. If `zoom` is not specified in the constructor options, MapLibre GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`.\n * @defaultValue 0\n */\n zoom?: number;\n /**\n * The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If `bearing` is not specified in the constructor options, MapLibre GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`.\n * @defaultValue 0\n */\n bearing?: number;\n /**\n * The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-85). If `pitch` is not specified in the constructor options, MapLibre GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`. Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.\n * @defaultValue 0\n */\n pitch?: number;\n /**\n * If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:\n *\n * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire\n * container, there will be blank space beyond 180 and -180 degrees longitude.\n * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the\n * map and the other on the left edge of the map) at every zoom level.\n * @defaultValue true\n */\n renderWorldCopies?: boolean;\n /**\n * The maximum number of tiles stored in the tile cache for a given source. If omitted, the cache will be dynamically sized based on the current viewport which can be set using `maxTileCacheZoomLevels` constructor options.\n * @defaultValue null\n */\n maxTileCacheSize?: number | null;\n /**\n * The maximum number of zoom levels for which to store tiles for a given source. Tile cache dynamic size is calculated by multiplying `maxTileCacheZoomLevels` with the approximate number of tiles in the viewport for a given source.\n * @defaultValue 5\n */\n maxTileCacheZoomLevels?: number;\n /**\n * A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests.\n * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties.\n * @defaultValue null\n */\n transformRequest?: RequestTransformFunction | null;\n /**\n * A callback run before the map's camera is moved due to user input or animation. The callback can be used to modify the new center, zoom, pitch and bearing.\n * Expected to return an object containing center, zoom, pitch or bearing values to overwrite.\n * @defaultValue null\n */\n transformCameraUpdate?: CameraUpdateTransformFunction | null;\n /**\n * A patch to apply to the default localization table for UI strings, e.g. control tooltips. The `locale` object maps namespaced UI string IDs to translated strings in the target language; see `src/ui/default_locale.js` for an example with all supported string IDs. The object may specify all UI strings (thereby adding support for a new translation) or only a subset of strings (thereby patching the default translation table).\n * @defaultValue null\n */\n locale?: any;\n /**\n * Controls the duration of the fade-in/fade-out animation for label collisions after initial map load, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading.\n * @defaultValue 300\n */\n fadeDuration?: number;\n /**\n * If `true`, symbols from multiple sources can collide with each other during collision detection. If `false`, collision detection is run separately for the symbols in each source.\n * @defaultValue true\n */\n crossSourceCollisions?: boolean;\n /**\n * If `true`, Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers (this information is normally inaccessible from the main Javascript thread). Information will be returned in a `resourceTiming` property of relevant `data` events.\n * @defaultValue false\n */\n collectResourceTiming?: boolean;\n /**\n * The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag).\n * @defaultValue 3\n */\n clickTolerance?: number;\n /**\n * The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options.\n */\n bounds?: LngLatBoundsLike;\n /**\n * A {@link FitBoundsOptions} options object to use _only_ when fitting the initial `bounds` provided above.\n */\n fitBoundsOptions?: FitBoundsOptions;\n /**\n * Defines a CSS\n * font-family for locally overriding generation of Chinese, Japanese, and Korean characters.\n * For these characters, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).\n * Set to `false`, to enable font settings from the map's style for these glyph ranges.\n * The purpose of this option is to avoid bandwidth-intensive glyph server requests. (See [Use locally generated ideographs](https://maplibre.org/maplibre-gl-js/docs/examples/local-ideographs).)\n * @defaultValue 'sans-serif'\n */\n localIdeographFontFamily?: string | false;\n /**\n * The map's MapLibre style. This must be a JSON object conforming to\n * the schema described in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/),\n * or a URL to such JSON.\n * When the style is not specified, calling {@link Map#setStyle} is required to render the map.\n */\n style?: StyleSpecification | string;\n /**\n * If `false`, the map's pitch (tilt) control with \"drag to rotate\" interaction will be disabled.\n * @defaultValue true\n */\n pitchWithRotate?: boolean;\n /**\n * The pixel ratio.\n * The canvas' `width` attribute will be `container.clientWidth * pixelRatio` and its `height` attribute will be `container.clientHeight * pixelRatio`. Defaults to `devicePixelRatio` if not specified.\n */\n pixelRatio?: number;\n /**\n * If false, style validation will be skipped. Useful in production environment.\n * @defaultValue true\n */\n validateStyle?: boolean;\n /**\n * The canvas' `width` and `height` max size. The values are passed as an array where the first element is max width and the second element is max height.\n * You shouldn't set this above WebGl `MAX_TEXTURE_SIZE`.\n * @defaultValue [4096, 4096].\n */\n maxCanvasSize?: [number, number];\n /**\n * Determines whether to cancel, or retain, tiles from the current viewport which are still loading but which belong to a farther (smaller) zoom level than the current one.\n * * If `true`, when zooming in, tiles which didn't manage to load for previous zoom levels will become canceled. This might save some computing resources for slower devices, but the map details might appear more abruptly at the end of the zoom.\n * * If `false`, when zooming in, the previous zoom level(s) tiles will progressively appear, giving a smoother map details experience. However, more tiles will be rendered in a short period of time.\n * @defaultValue true\n */\n cancelPendingTileRequestsWhileZooming?: boolean;\n};\n\nexport type AddImageOptions = {\n\n}\n\n// This type is used inside map since all properties are assigned a default value.\nexport type CompleteMapOptions = Complete;\n\ntype DelegatedListener = {\n layers: string[];\n listener: Listener;\n delegates: {[E in keyof MapEventType]?: Delegate};\n}\n\ntype Delegate = (e: E) => void;\n\nconst defaultMinZoom = -2;\nconst defaultMaxZoom = 22;\n\n// the default values, but also the valid range\nconst defaultMinPitch = 0;\nconst defaultMaxPitch = 60;\n\n// use this variable to check maxPitch for validity\nconst maxPitchThreshold = 85;\n\nconst defaultOptions: Readonly> = {\n hash: false,\n interactive: true,\n bearingSnap: 7,\n attributionControl: defaultAttributionControlOptions,\n maplibreLogo: false,\n failIfMajorPerformanceCaveat: false,\n preserveDrawingBuffer: false,\n refreshExpiredTiles: true,\n\n scrollZoom: true,\n minZoom: defaultMinZoom,\n maxZoom: defaultMaxZoom,\n minPitch: defaultMinPitch,\n maxPitch: defaultMaxPitch,\n\n boxZoom: true,\n dragRotate: true,\n dragPan: true,\n keyboard: true,\n doubleClickZoom: true,\n touchZoomRotate: true,\n touchPitch: true,\n cooperativeGestures: false,\n\n trackResize: true,\n\n center: [0, 0],\n zoom: 0,\n bearing: 0,\n pitch: 0,\n\n renderWorldCopies: true,\n maxTileCacheSize: null,\n maxTileCacheZoomLevels: config.MAX_TILE_CACHE_ZOOM_LEVELS,\n transformRequest: null,\n transformCameraUpdate: null,\n fadeDuration: 300,\n crossSourceCollisions: true,\n clickTolerance: 3,\n localIdeographFontFamily: 'sans-serif',\n pitchWithRotate: true,\n validateStyle: true,\n /**Because GL MAX_TEXTURE_SIZE is usually at least 4096px. */\n maxCanvasSize: [4096, 4096],\n cancelPendingTileRequestsWhileZooming: true\n};\n\n/**\n * The `Map` object represents the map on your page. It exposes methods\n * and properties that enable you to programmatically change the map,\n * and fires events as users interact with it.\n *\n * You create a `Map` by specifying a `container` and other options, see {@link MapOptions} for the full list.\n * Then MapLibre GL JS initializes the map on the page and returns your `Map` object.\n *\n * @group Main\n *\n * @example\n * ```ts\n * let map = new Map({\n * container: 'map',\n * center: [-122.420679, 37.772537],\n * zoom: 13,\n * style: style_object,\n * hash: true,\n * transformRequest: (url, resourceType)=> {\n * if(resourceType === 'Source' && url.startsWith('http://myHost')) {\n * return {\n * url: url.replace('http', 'https'),\n * headers: { 'my-custom-header': true},\n * credentials: 'include' // Include cookies for cross-origin requests\n * }\n * }\n * }\n * });\n * ```\n * @see [Display a map](https://maplibre.org/maplibre-gl-js/docs/examples/simple-map/)\n */\nexport class Map extends Camera {\n style: Style;\n painter: Painter;\n\n _container: HTMLElement;\n _canvasContainer: HTMLElement;\n _controlContainer: HTMLElement;\n _controlPositions: Record;\n _interactive: boolean;\n _showTileBoundaries: boolean;\n _showCollisionBoxes: boolean;\n _showPadding: boolean;\n _showOverdrawInspector: boolean;\n _repaint: boolean;\n _vertices: boolean;\n _canvas: HTMLCanvasElement;\n _maxTileCacheSize: number | null;\n _maxTileCacheZoomLevels: number;\n _frameRequest: AbortController;\n _styleDirty: boolean;\n _sourcesDirty: boolean;\n _placementDirty: boolean;\n\n _loaded: boolean;\n _idleTriggered = false;\n // accounts for placement finishing as well\n _fullyLoaded: boolean;\n _trackResize: boolean;\n _resizeObserver: ResizeObserver;\n _preserveDrawingBuffer: boolean;\n _failIfMajorPerformanceCaveat: boolean;\n _antialias: boolean;\n _refreshExpiredTiles: boolean;\n _hash: Hash;\n _delegatedListeners: Record;\n _fadeDuration: number;\n _crossSourceCollisions: boolean;\n _crossFadingFactor = 1;\n _collectResourceTiming: boolean;\n _renderTaskQueue = new TaskQueue();\n _controls: Array = [];\n _mapId = uniqueId();\n _localIdeographFontFamily: string | false;\n _validateStyle: boolean;\n _requestManager: RequestManager;\n _locale: typeof defaultLocale;\n _removed: boolean;\n _clickTolerance: number;\n _overridePixelRatio: number | null | undefined;\n _maxCanvasSize: [number, number];\n _terrainDataCallback: (e: MapStyleDataEvent | MapSourceDataEvent) => void;\n\n /**\n * @internal\n * image queue throttling handle. To be used later when clean up\n */\n _imageQueueHandle: number;\n\n /**\n * The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad.\n * Find more details and examples using `scrollZoom` in the {@link ScrollZoomHandler} section.\n */\n scrollZoom: ScrollZoomHandler;\n\n /**\n * The map's {@link BoxZoomHandler}, which implements zooming using a drag gesture with the Shift key pressed.\n * Find more details and examples using `boxZoom` in the {@link BoxZoomHandler} section.\n */\n boxZoom: BoxZoomHandler;\n\n /**\n * The map's {@link DragRotateHandler}, which implements rotating the map while dragging with the right\n * mouse button or with the Control key pressed. Find more details and examples using `dragRotate`\n * in the {@link DragRotateHandler} section.\n */\n dragRotate: DragRotateHandler;\n\n /**\n * The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture.\n * Find more details and examples using `dragPan` in the {@link DragPanHandler} section.\n */\n dragPan: DragPanHandler;\n\n /**\n * The map's {@link KeyboardHandler}, which allows the user to zoom, rotate, and pan the map using keyboard\n * shortcuts. Find more details and examples using `keyboard` in the {@link KeyboardHandler} section.\n */\n keyboard: KeyboardHandler;\n\n /**\n * The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking.\n * Find more details and examples using `doubleClickZoom` in the {@link DoubleClickZoomHandler} section.\n */\n doubleClickZoom: DoubleClickZoomHandler;\n\n /**\n * The map's {@link TwoFingersTouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures.\n * Find more details and examples using `touchZoomRotate` in the {@link TwoFingersTouchZoomRotateHandler} section.\n */\n touchZoomRotate: TwoFingersTouchZoomRotateHandler;\n\n /**\n * The map's {@link TwoFingersTouchPitchHandler}, which allows the user to pitch the map with touch gestures.\n * Find more details and examples using `touchPitch` in the {@link TwoFingersTouchPitchHandler} section.\n */\n touchPitch: TwoFingersTouchPitchHandler;\n\n /**\n * The map's {@link CooperativeGesturesHandler}, which allows the user to see cooperative gesture info when user tries to zoom in/out.\n * Find more details and examples using `cooperativeGestures` in the {@link CooperativeGesturesHandler} section.\n */\n cooperativeGestures: CooperativeGesturesHandler;\n\n /**\n * The map's property which determines whether to cancel, or retain, tiles from the current viewport which are still loading but which belong to a farther (smaller) zoom level than the current one.\n * * If `true`, when zooming in, tiles which didn't manage to load for previous zoom levels will become canceled. This might save some computing resources for slower devices, but the map details might appear more abruptly at the end of the zoom.\n * * If `false`, when zooming in, the previous zoom level(s) tiles will progressively appear, giving a smoother map details experience. However, more tiles will be rendered in a short period of time.\n * @defaultValue true\n */\n cancelPendingTileRequestsWhileZooming: boolean;\n\n constructor(options: MapOptions) {\n PerformanceUtils.mark(PerformanceMarkers.create);\n\n const resolvedOptions = {...defaultOptions, ...options} as CompleteMapOptions;\n\n if (resolvedOptions.minZoom != null && resolvedOptions.maxZoom != null && resolvedOptions.minZoom > resolvedOptions.maxZoom) {\n throw new Error('maxZoom must be greater than or equal to minZoom');\n }\n\n if (resolvedOptions.minPitch != null && resolvedOptions.maxPitch != null && resolvedOptions.minPitch > resolvedOptions.maxPitch) {\n throw new Error('maxPitch must be greater than or equal to minPitch');\n }\n\n if (resolvedOptions.minPitch != null && resolvedOptions.minPitch < defaultMinPitch) {\n throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);\n }\n\n if (resolvedOptions.maxPitch != null && resolvedOptions.maxPitch > maxPitchThreshold) {\n throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`);\n }\n\n const transform = new Transform(resolvedOptions.minZoom, resolvedOptions.maxZoom, resolvedOptions.minPitch, resolvedOptions.maxPitch, resolvedOptions.renderWorldCopies);\n super(transform, {bearingSnap: resolvedOptions.bearingSnap});\n\n this._interactive = resolvedOptions.interactive;\n this._maxTileCacheSize = resolvedOptions.maxTileCacheSize;\n this._maxTileCacheZoomLevels = resolvedOptions.maxTileCacheZoomLevels;\n this._failIfMajorPerformanceCaveat = resolvedOptions.failIfMajorPerformanceCaveat === true;\n this._preserveDrawingBuffer = resolvedOptions.preserveDrawingBuffer === true;\n this._antialias = resolvedOptions.antialias === true;\n this._trackResize = resolvedOptions.trackResize === true;\n this._bearingSnap = resolvedOptions.bearingSnap;\n this._refreshExpiredTiles = resolvedOptions.refreshExpiredTiles === true;\n this._fadeDuration = resolvedOptions.fadeDuration;\n this._crossSourceCollisions = resolvedOptions.crossSourceCollisions === true;\n this._collectResourceTiming = resolvedOptions.collectResourceTiming === true;\n this._locale = {...defaultLocale, ...resolvedOptions.locale};\n this._clickTolerance = resolvedOptions.clickTolerance;\n this._overridePixelRatio = resolvedOptions.pixelRatio;\n this._maxCanvasSize = resolvedOptions.maxCanvasSize;\n this.transformCameraUpdate = resolvedOptions.transformCameraUpdate;\n this.cancelPendingTileRequestsWhileZooming = resolvedOptions.cancelPendingTileRequestsWhileZooming === true;\n\n this._imageQueueHandle = ImageRequest.addThrottleControl(() => this.isMoving());\n\n this._requestManager = new RequestManager(resolvedOptions.transformRequest);\n\n if (typeof resolvedOptions.container === 'string') {\n this._container = document.getElementById(resolvedOptions.container);\n if (!this._container) {\n throw new Error(`Container '${resolvedOptions.container}' not found.`);\n }\n } else if (resolvedOptions.container instanceof HTMLElement) {\n this._container = resolvedOptions.container;\n } else {\n throw new Error('Invalid type: \\'container\\' must be a String or HTMLElement.');\n }\n\n if (resolvedOptions.maxBounds) {\n this.setMaxBounds(resolvedOptions.maxBounds);\n }\n\n this._setupContainer();\n this._setupPainter();\n\n this.on('move', () => this._update(false))\n .on('moveend', () => this._update(false))\n .on('zoom', () => this._update(true))\n .on('terrain', () => {\n this.painter.terrainFacilitator.dirty = true;\n this._update(true);\n })\n .once('idle', () => { this._idleTriggered = true; });\n\n if (typeof window !== 'undefined') {\n addEventListener('online', this._onWindowOnline, false);\n let initialResizeEventCaptured = false;\n const throttledResizeCallback = throttle((entries: ResizeObserverEntry[]) => {\n if (this._trackResize && !this._removed) {\n this.resize(entries);\n this.redraw();\n }\n }, 50);\n this._resizeObserver = new ResizeObserver((entries) => {\n if (!initialResizeEventCaptured) {\n initialResizeEventCaptured = true;\n return;\n }\n throttledResizeCallback(entries);\n });\n this._resizeObserver.observe(this._container);\n }\n\n this.handlers = new HandlerManager(this, resolvedOptions);\n\n const hashName = (typeof resolvedOptions.hash === 'string' && resolvedOptions.hash) || undefined;\n this._hash = resolvedOptions.hash && (new Hash(hashName)).addTo(this);\n // don't set position from options if set through hash\n if (!this._hash || !this._hash._onHashChange()) {\n this.jumpTo({\n center: resolvedOptions.center,\n zoom: resolvedOptions.zoom,\n bearing: resolvedOptions.bearing,\n pitch: resolvedOptions.pitch\n });\n\n if (resolvedOptions.bounds) {\n this.resize();\n this.fitBounds(resolvedOptions.bounds, extend({}, resolvedOptions.fitBoundsOptions, {duration: 0}));\n }\n }\n\n this.resize();\n\n this._localIdeographFontFamily = resolvedOptions.localIdeographFontFamily;\n this._validateStyle = resolvedOptions.validateStyle;\n\n if (resolvedOptions.style) this.setStyle(resolvedOptions.style, {localIdeographFontFamily: resolvedOptions.localIdeographFontFamily});\n\n if (resolvedOptions.attributionControl)\n this.addControl(new AttributionControl(typeof resolvedOptions.attributionControl === 'boolean' ? undefined : resolvedOptions.attributionControl));\n\n if (resolvedOptions.maplibreLogo)\n this.addControl(new LogoControl(), resolvedOptions.logoPosition);\n\n this.on('style.load', () => {\n if (this.transform.unmodified) {\n this.jumpTo(this.style.stylesheet as any);\n }\n });\n this.on('data', (event: MapDataEvent) => {\n this._update(event.dataType === 'style');\n this.fire(new Event(`${event.dataType}data`, event));\n });\n this.on('dataloading', (event: MapDataEvent) => {\n this.fire(new Event(`${event.dataType}dataloading`, event));\n });\n this.on('dataabort', (event: MapDataEvent) => {\n this.fire(new Event('sourcedataabort', event));\n });\n }\n\n /**\n * @internal\n * Returns a unique number for this map instance which is used for the MapLoadEvent\n * to make sure we only fire one event per instantiated map object.\n * @returns the uniq map ID\n */\n _getMapId() {\n return this._mapId;\n }\n\n /**\n * Adds an {@link IControl} to the map, calling `control.onAdd(this)`.\n *\n * An {@link ErrorEvent} will be fired if the image parameter is invald.\n *\n * @param control - The {@link IControl} to add.\n * @param position - position on the map to which the control will be added.\n * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`.\n * @example\n * Add zoom and rotation controls to the map.\n * ```ts\n * map.addControl(new NavigationControl());\n * ```\n * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/)\n */\n addControl(control: IControl, position?: ControlPosition): Map {\n if (position === undefined) {\n if (control.getDefaultPosition) {\n position = control.getDefaultPosition();\n } else {\n position = 'top-right';\n }\n }\n if (!control || !control.onAdd) {\n return this.fire(new ErrorEvent(new Error(\n 'Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.')));\n }\n const controlElement = control.onAdd(this);\n this._controls.push(control);\n\n const positionContainer = this._controlPositions[position];\n if (position.indexOf('bottom') !== -1) {\n positionContainer.insertBefore(controlElement, positionContainer.firstChild);\n } else {\n positionContainer.appendChild(controlElement);\n }\n return this;\n }\n\n /**\n * Removes the control from the map.\n *\n * An {@link ErrorEvent} will be fired if the image parameter is invald.\n *\n * @param control - The {@link IControl} to remove.\n * @example\n * ```ts\n * // Define a new navigation control.\n * let navigation = new NavigationControl();\n * // Add zoom and rotation controls to the map.\n * map.addControl(navigation);\n * // Remove zoom and rotation controls from the map.\n * map.removeControl(navigation);\n * ```\n */\n removeControl(control: IControl): Map {\n if (!control || !control.onRemove) {\n return this.fire(new ErrorEvent(new Error(\n 'Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.')));\n }\n const ci = this._controls.indexOf(control);\n if (ci > -1) this._controls.splice(ci, 1);\n control.onRemove(this);\n return this;\n }\n\n /**\n * Checks if a control exists on the map.\n *\n * @param control - The {@link IControl} to check.\n * @returns true if map contains control.\n * @example\n * ```ts\n * // Define a new navigation control.\n * let navigation = new NavigationControl();\n * // Add zoom and rotation controls to the map.\n * map.addControl(navigation);\n * // Check that the navigation control exists on the map.\n * map.hasControl(navigation);\n * ```\n */\n hasControl(control: IControl): boolean {\n return this._controls.indexOf(control) > -1;\n }\n\n calculateCameraOptionsFromTo(from: LngLat, altitudeFrom: number, to: LngLat, altitudeTo?: number): CameraOptions {\n if (altitudeTo == null && this.terrain) {\n altitudeTo = this.terrain.getElevationForLngLatZoom(to, this.transform.tileZoom);\n }\n return super.calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo);\n }\n\n /**\n * Resizes the map according to the dimensions of its\n * `container` element.\n *\n * Checks if the map container size changed and updates the map if it has changed.\n * This method must be called after the map's `container` is resized programmatically\n * or when the map is shown after being initially hidden with CSS.\n *\n * Triggers the following events: `movestart`, `move`, `moveend`, and `resize`.\n *\n * @param eventData - Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend`\n * events that get triggered as a result of resize. This can be useful for differentiating the\n * source of an event (for example, user-initiated or programmatically-triggered events).\n * @example\n * Resize the map when the map container is shown after being initially hidden with CSS.\n * ```ts\n * let mapDiv = document.getElementById('map');\n * if (mapDiv.style.visibility === true) map.resize();\n * ```\n */\n resize(eventData?: any): Map {\n const dimensions = this._containerDimensions();\n const width = dimensions[0];\n const height = dimensions[1];\n\n const clampedPixelRatio = this._getClampedPixelRatio(width, height);\n this._resizeCanvas(width, height, clampedPixelRatio);\n this.painter.resize(width, height, clampedPixelRatio);\n\n // check if we've reached GL limits, in that case further clamps pixelRatio\n if (this.painter.overLimit()) {\n const gl = this.painter.context.gl;\n // store updated _maxCanvasSize value\n this._maxCanvasSize = [gl.drawingBufferWidth, gl.drawingBufferHeight];\n const clampedPixelRatio = this._getClampedPixelRatio(width, height);\n this._resizeCanvas(width, height, clampedPixelRatio);\n this.painter.resize(width, height, clampedPixelRatio);\n }\n\n this.transform.resize(width, height);\n this._requestedCameraState?.resize(width, height);\n\n const fireMoving = !this._moving;\n if (fireMoving) {\n this.stop();\n this.fire(new Event('movestart', eventData))\n .fire(new Event('move', eventData));\n }\n\n this.fire(new Event('resize', eventData));\n\n if (fireMoving) this.fire(new Event('moveend', eventData));\n\n return this;\n }\n\n /**\n * @internal\n * Return the map's pixel ratio eventually scaled down to respect maxCanvasSize.\n * Internally you should use this and not getPixelRatio().\n */\n _getClampedPixelRatio(width: number, height: number): number {\n const {0: maxCanvasWidth, 1: maxCanvasHeight} = this._maxCanvasSize;\n const pixelRatio = this.getPixelRatio();\n\n const canvasWidth = width * pixelRatio;\n const canvasHeight = height * pixelRatio;\n\n const widthScaleFactor = canvasWidth > maxCanvasWidth ? (maxCanvasWidth / canvasWidth) : 1;\n const heightScaleFactor = canvasHeight > maxCanvasHeight ? (maxCanvasHeight / canvasHeight) : 1;\n\n return Math.min(widthScaleFactor, heightScaleFactor) * pixelRatio;\n }\n\n /**\n * Returns the map's pixel ratio.\n * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.\n * @returns The pixel ratio.\n */\n getPixelRatio(): number {\n return this._overridePixelRatio ?? devicePixelRatio;\n }\n\n /**\n * Sets the map's pixel ratio. This allows to override `devicePixelRatio`.\n * After this call, the canvas' `width` attribute will be `container.clientWidth * pixelRatio`\n * and its height attribute will be `container.clientHeight * pixelRatio`.\n * Set this to null to disable `devicePixelRatio` override.\n * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.\n * @param pixelRatio - The pixel ratio.\n */\n setPixelRatio(pixelRatio: number) {\n this._overridePixelRatio = pixelRatio;\n this.resize();\n }\n\n /**\n * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not\n * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.\n * @returns The geographical bounds of the map as {@link LngLatBounds}.\n * @example\n * ```ts\n * let bounds = map.getBounds();\n * ```\n */\n getBounds(): LngLatBounds {\n return this.transform.getBounds();\n }\n\n /**\n * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.\n * @returns The map object.\n * @example\n * ```ts\n * let maxBounds = map.getMaxBounds();\n * ```\n */\n getMaxBounds(): LngLatBounds | null {\n return this.transform.getMaxBounds();\n }\n\n /**\n * Sets or clears the map's geographical bounds.\n *\n * Pan and zoom operations are constrained within these bounds.\n * If a pan or zoom is performed that would\n * display regions outside these bounds, the map will\n * instead display a position and zoom level\n * as close as possible to the operation's request while still\n * remaining within the bounds.\n *\n * @param bounds - The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds.\n * @example\n * Define bounds that conform to the `LngLatBoundsLike` object as set the max bounds.\n * ```ts\n * let bounds = [\n * [-74.04728, 40.68392], // [west, south]\n * [-73.91058, 40.87764] // [east, north]\n * ];\n * map.setMaxBounds(bounds);\n * ```\n */\n setMaxBounds(bounds?: LngLatBoundsLike | null): Map {\n this.transform.setMaxBounds(LngLatBounds.convert(bounds));\n return this._update();\n }\n\n /**\n * Sets or clears the map's minimum zoom level.\n * If the map's current zoom level is lower than the new minimum,\n * the map will zoom to the new minimum.\n *\n * It is not always possible to zoom out and reach the set `minZoom`.\n * Other factors such as map height may restrict zooming. For example,\n * if the map is 512px tall it will not be possible to zoom below zoom 0\n * no matter what the `minZoom` is set to.\n *\n * A {@link ErrorEvent} event will be fired if minZoom is out of bounds.\n *\n * @param minZoom - The minimum zoom level to set (-2 - 24).\n * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2).\n * @example\n * ```ts\n * map.setMinZoom(12.25);\n * ```\n */\n setMinZoom(minZoom?: number | null): Map {\n\n minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom;\n\n if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) {\n this.transform.minZoom = minZoom;\n this._update();\n\n if (this.getZoom() < minZoom) this.setZoom(minZoom);\n\n return this;\n\n } else throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`);\n }\n\n /**\n * Returns the map's minimum allowable zoom level.\n *\n * @returns minZoom\n * @example\n * ```ts\n * let minZoom = map.getMinZoom();\n * ```\n */\n getMinZoom(): number { return this.transform.minZoom; }\n\n /**\n * Sets or clears the map's maximum zoom level.\n * If the map's current zoom level is higher than the new maximum,\n * the map will zoom to the new maximum.\n *\n * A {@link ErrorEvent} event will be fired if minZoom is out of bounds.\n *\n * @param maxZoom - The maximum zoom level to set.\n * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22).\n * @example\n * ```ts\n * map.setMaxZoom(18.75);\n * ```\n */\n setMaxZoom(maxZoom?: number | null): Map {\n\n maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom;\n\n if (maxZoom >= this.transform.minZoom) {\n this.transform.maxZoom = maxZoom;\n this._update();\n\n if (this.getZoom() > maxZoom) this.setZoom(maxZoom);\n\n return this;\n\n } else throw new Error('maxZoom must be greater than the current minZoom');\n }\n\n /**\n * Returns the map's maximum allowable zoom level.\n *\n * @returns The maxZoom\n * @example\n * ```ts\n * let maxZoom = map.getMaxZoom();\n * ```\n */\n getMaxZoom(): number { return this.transform.maxZoom; }\n\n /**\n * Sets or clears the map's minimum pitch.\n * If the map's current pitch is lower than the new minimum,\n * the map will pitch to the new minimum.\n *\n * A {@link ErrorEvent} event will be fired if minPitch is out of bounds.\n *\n * @param minPitch - The minimum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.\n * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0).\n */\n setMinPitch(minPitch?: number | null): Map {\n\n minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch;\n\n if (minPitch < defaultMinPitch) {\n throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);\n }\n\n if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) {\n this.transform.minPitch = minPitch;\n this._update();\n\n if (this.getPitch() < minPitch) this.setPitch(minPitch);\n\n return this;\n\n } else throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`);\n }\n\n /**\n * Returns the map's minimum allowable pitch.\n *\n * @returns The minPitch\n */\n getMinPitch(): number { return this.transform.minPitch; }\n\n /**\n * Sets or clears the map's maximum pitch.\n * If the map's current pitch is higher than the new maximum,\n * the map will pitch to the new maximum.\n *\n * A {@link ErrorEvent} event will be fired if maxPitch is out of bounds.\n *\n * @param maxPitch - The maximum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.\n * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60).\n */\n setMaxPitch(maxPitch?: number | null): Map {\n\n maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch;\n\n if (maxPitch > maxPitchThreshold) {\n throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`);\n }\n\n if (maxPitch >= this.transform.minPitch) {\n this.transform.maxPitch = maxPitch;\n this._update();\n\n if (this.getPitch() > maxPitch) this.setPitch(maxPitch);\n\n return this;\n\n } else throw new Error('maxPitch must be greater than the current minPitch');\n }\n\n /**\n * Returns the map's maximum allowable pitch.\n *\n * @returns The maxPitch\n */\n getMaxPitch(): number { return this.transform.maxPitch; }\n\n /**\n * Returns the state of `renderWorldCopies`. If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:\n *\n * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire\n * container, there will be blank space beyond 180 and -180 degrees longitude.\n * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the\n * map and the other on the left edge of the map) at every zoom level.\n * @returns The renderWorldCopies\n * @example\n * ```ts\n * let worldCopiesRendered = map.getRenderWorldCopies();\n * ```\n * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/)\n */\n getRenderWorldCopies(): boolean { return this.transform.renderWorldCopies; }\n\n /**\n * Sets the state of `renderWorldCopies`.\n *\n * @param renderWorldCopies - If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:\n *\n * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire\n * container, there will be blank space beyond 180 and -180 degrees longitude.\n * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the\n * map and the other on the left edge of the map) at every zoom level.\n *\n * `undefined` is treated as `true`, `null` is treated as `false`.\n * @example\n * ```ts\n * map.setRenderWorldCopies(true);\n * ```\n * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/)\n */\n setRenderWorldCopies(renderWorldCopies?: boolean | null): Map {\n this.transform.renderWorldCopies = renderWorldCopies;\n return this._update();\n }\n\n /**\n * Returns a [Point](https://github.com/mapbox/point-geometry) representing pixel coordinates, relative to the map's `container`,\n * that correspond to the specified geographical location.\n *\n * @param lnglat - The geographical location to project.\n * @returns The [Point](https://github.com/mapbox/point-geometry) corresponding to `lnglat`, relative to the map's `container`.\n * @example\n * ```ts\n * let coordinate = [-122.420679, 37.772537];\n * let point = map.project(coordinate);\n * ```\n */\n project(lnglat: LngLatLike): Point {\n return this.transform.locationPoint(LngLat.convert(lnglat), this.style && this.terrain);\n }\n\n /**\n * Returns a {@link LngLat} representing geographical coordinates that correspond\n * to the specified pixel coordinates.\n *\n * @param point - The pixel coordinates to unproject.\n * @returns The {@link LngLat} corresponding to `point`.\n * @example\n * ```ts\n * map.on('click', (e) => {\n * // When the map is clicked, get the geographic coordinate.\n * let coordinate = map.unproject(e.point);\n * });\n * ```\n */\n unproject(point: PointLike): LngLat {\n return this.transform.pointLocation(Point.convert(point), this.terrain);\n }\n\n /**\n * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.\n * @returns true if the map is moving.\n * @example\n * ```ts\n * let isMoving = map.isMoving();\n * ```\n */\n isMoving(): boolean {\n return this._moving || this.handlers?.isMoving();\n }\n\n /**\n * Returns true if the map is zooming due to a camera animation or user gesture.\n * @returns true if the map is zooming.\n * @example\n * ```ts\n * let isZooming = map.isZooming();\n * ```\n */\n isZooming(): boolean {\n return this._zooming || this.handlers?.isZooming();\n }\n\n /**\n * Returns true if the map is rotating due to a camera animation or user gesture.\n * @returns true if the map is rotating.\n * @example\n * ```ts\n * map.isRotating();\n * ```\n */\n isRotating(): boolean {\n return this._rotating || this.handlers?.isRotating();\n }\n\n _createDelegatedListener(type: keyof MapEventType | string, layerIds: string[], listener: Listener): DelegatedListener {\n if (type === 'mouseenter' || type === 'mouseover') {\n let mousein = false;\n const mousemove = (e) => {\n const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId));\n const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, {layers: existingLayers}) : [];\n if (!features.length) {\n mousein = false;\n } else if (!mousein) {\n mousein = true;\n listener.call(this, new MapMouseEvent(type, this, e.originalEvent, {features}));\n }\n };\n const mouseout = () => {\n mousein = false;\n };\n return {layers: layerIds, listener, delegates: {mousemove, mouseout}};\n } else if (type === 'mouseleave' || type === 'mouseout') {\n let mousein = false;\n const mousemove = (e) => {\n const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId));\n const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, {layers: existingLayers}) : [];\n if (features.length) {\n mousein = true;\n } else if (mousein) {\n mousein = false;\n listener.call(this, new MapMouseEvent(type, this, e.originalEvent));\n }\n };\n const mouseout = (e) => {\n if (mousein) {\n mousein = false;\n listener.call(this, new MapMouseEvent(type, this, e.originalEvent));\n }\n };\n return {layers: layerIds, listener, delegates: {mousemove, mouseout}};\n } else {\n const delegate = (e) => {\n const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId));\n const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, {layers: existingLayers}) : [];\n if (features.length) {\n // Here we need to mutate the original event, so that preventDefault works as expected.\n e.features = features;\n listener.call(this, e);\n delete e.features;\n }\n };\n return {layers: layerIds, listener, delegates: {[type]: delegate}};\n }\n }\n\n _saveDelegatedListener(type: keyof MapEventType | string, delegatedListener: DelegatedListener): void {\n this._delegatedListeners = this._delegatedListeners || {};\n this._delegatedListeners[type] = this._delegatedListeners[type] || [];\n this._delegatedListeners[type].push(delegatedListener);\n }\n\n _removeDelegatedListener(type: string, layerIds: string[], listener: Listener) {\n if (!this._delegatedListeners || !this._delegatedListeners[type]) {\n return;\n }\n\n const listeners = this._delegatedListeners[type];\n for (let i = 0; i < listeners.length; i++) {\n const delegatedListener = listeners[i];\n if (\n delegatedListener.listener === listener &&\n delegatedListener.layers.length === layerIds.length &&\n delegatedListener.layers.every((layerId: string) => layerIds.includes(layerId))\n ) {\n for (const event in delegatedListener.delegates) {\n this.off(event, delegatedListener.delegates[event]);\n }\n listeners.splice(i, 1);\n return;\n }\n }\n }\n\n /**\n * @event\n * Adds a listener for events of a specified type, optionally limited to features in a specified style layer(s).\n * See {@link MapEventType} and {@link MapLayerEventType} for a full list of events and their description.\n *\n * | Event | Compatible with `layerId` |\n * |------------------------|---------------------------|\n * | `mousedown` | yes |\n * | `mouseup` | yes |\n * | `mouseover` | yes |\n * | `mouseout` | yes |\n * | `mousemove` | yes |\n * | `mouseenter` | yes (required) |\n * | `mouseleave` | yes (required) |\n * | `click` | yes |\n * | `dblclick` | yes |\n * | `contextmenu` | yes |\n * | `touchstart` | yes |\n * | `touchend` | yes |\n * | `touchcancel` | yes |\n * | `wheel` | |\n * | `resize` | |\n * | `remove` | |\n * | `touchmove` | |\n * | `movestart` | |\n * | `move` | |\n * | `moveend` | |\n * | `dragstart` | |\n * | `drag` | |\n * | `dragend` | |\n * | `zoomstart` | |\n * | `zoom` | |\n * | `zoomend` | |\n * | `rotatestart` | |\n * | `rotate` | |\n * | `rotateend` | |\n * | `pitchstart` | |\n * | `pitch` | |\n * | `pitchend` | |\n * | `boxzoomstart` | |\n * | `boxzoomend` | |\n * | `boxzoomcancel` | |\n * | `webglcontextlost` | |\n * | `webglcontextrestored` | |\n * | `load` | |\n * | `render` | |\n * | `idle` | |\n * | `error` | |\n * | `data` | |\n * | `styledata` | |\n * | `sourcedata` | |\n * | `dataloading` | |\n * | `styledataloading` | |\n * | `sourcedataloading` | |\n * | `styleimagemissing` | |\n * | `dataabort` | |\n * | `sourcedataabort` | |\n *\n * @param type - The event type to listen for. Events compatible with the optional `layerId` parameter are triggered\n * when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.\n * @param layer - The ID of a style layer or a listener if no ID is provided. Event will only be triggered if its location\n * is within a visible feature in this layer. The event will have a `features` property containing\n * an array of the matching features. If `layer` is not supplied, the event will not have a `features` property.\n * Please note that many event types are not compatible with the optional `layer` parameter.\n * @param listener - The function to be called when the event is fired.\n * @example\n * ```ts\n * // Set an event listener that will fire\n * // when the map has finished loading\n * map.on('load', () => {\n * // Once the map has finished loading,\n * // add a new layer\n * map.addLayer({\n * id: 'points-of-interest',\n * source: {\n * type: 'vector',\n * url: 'https://maplibre.org/maplibre-style-spec/'\n * },\n * 'source-layer': 'poi_label',\n * type: 'circle',\n * paint: {\n * // MapLibre Style Specification paint properties\n * },\n * layout: {\n * // MapLibre Style Specification layout properties\n * }\n * });\n * });\n * ```\n * @example\n * ```ts\n * // Set an event listener that will fire\n * // when a feature on the countries layer of the map is clicked\n * map.on('click', 'countries', (e) => {\n * new Popup()\n * .setLngLat(e.lngLat)\n * .setHTML(`Country name: ${e.features[0].properties.name}`)\n * .addTo(map);\n * });\n * ```\n * @see [Display popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/)\n * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/)\n * @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/)\n * @see [Create a draggable marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n on(\n type: T,\n layer: string,\n listener: (ev: MapLayerEventType[T] & Object) => void,\n ): Map;\n /**\n * Overload of the `on` method that allows to listen to events specifying multiple layers.\n * @event\n * @param type - The type of the event.\n * @param layerIds - The array of style layer IDs.\n * @param listener - The listener callback.\n */\n on(\n type: T,\n layerIds: string[],\n listener: (ev: MapLayerEventType[T] & Object) => void\n ): this;\n /**\n * Overload of the `on` method that allows to listen to events without specifying a layer.\n * @event\n * @param type - The type of the event.\n * @param listener - The listener callback.\n */\n on(type: T, listener: (ev: MapEventType[T] & Object) => void): this;\n /**\n * Overload of the `on` method that allows to listen to events without specifying a layer.\n * @event\n * @param type - The type of the event.\n * @param listener - The listener callback.\n */\n on(type: keyof MapEventType | string, listener: Listener): this;\n on(type: keyof MapEventType | string, layerIdsOrListener: string | string[] | Listener, listener?: Listener): this {\n if (listener === undefined) {\n return super.on(type, layerIdsOrListener as Listener);\n }\n\n const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener as string[];\n\n const delegatedListener = this._createDelegatedListener(type, layerIds, listener);\n\n this._saveDelegatedListener(type, delegatedListener);\n\n for (const event in delegatedListener.delegates) {\n this.on(event, delegatedListener.delegates[event]);\n }\n\n return this;\n }\n\n /**\n * Adds a listener that will be called only once to a specified event type, optionally limited to features in a specified style layer.\n *\n * @event\n * @param type - The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'click'`, `'dblclick'`,\n * `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`,\n * `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters\n * a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave`\n * and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves\n * the map canvas.\n * @param layer - The ID of a style layer or a listener if no ID is provided. Only events whose location is within a visible\n * feature in this layer will trigger the listener. The event will have a `features` property containing\n * an array of the matching features.\n * @param listener - The function to be called when the event is fired.\n * @returns `this` if listener is provided, promise otherwise to allow easier usage of async/await\n */\n once(\n type: T,\n layer: string,\n listener?: (ev: MapLayerEventType[T] & Object) => void,\n ): this | Promise;\n /**\n * Overload of the `once` method that allows to listen to events specifying multiple layers.\n * @event\n * @param type - The type of the event.\n * @param layerIds - The array of style layer IDs.\n * @param listener - The listener callback.\n */\n once(\n type: T,\n layerIds: string[],\n listener?: (ev: MapLayerEventType[T] & Object) => void\n ): this | Promise;\n /**\n * Overload of the `once` method that allows to listen to events without specifying a layer.\n * @event\n * @param type - The type of the event.\n * @param listener - The listener callback.\n */\n once(type: T, listener?: (ev: MapEventType[T] & Object) => void): this | Promise;\n /**\n * Overload of the `once` method that allows to listen to events without specifying a layer.\n * @event\n * @param type - The type of the event.\n * @param listener - The listener callback.\n */\n once(type: keyof MapEventType | string, listener?: Listener): this | Promise;\n once(type: keyof MapEventType | string, layerIdsOrListener: string | string[] | Listener, listener?: Listener): this | Promise {\n if (listener === undefined) {\n return super.once(type, layerIdsOrListener as Listener);\n }\n\n const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener as string[];\n\n const delegatedListener = this._createDelegatedListener(type, layerIds, listener);\n\n for (const key in delegatedListener.delegates) {\n const delegate: Delegate = delegatedListener.delegates[key];\n delegatedListener.delegates[key] = (...args: Parameters) => {\n this._removeDelegatedListener(type, layerIds, listener);\n delegate(...args);\n };\n }\n\n this._saveDelegatedListener(type, delegatedListener);\n\n for (const event in delegatedListener.delegates) {\n this.once(event, delegatedListener.delegates[event]);\n }\n\n return this;\n }\n\n /**\n * Removes an event listener for events previously added with `Map#on`.\n *\n * @event\n * @param type - The event type previously used to install the listener.\n * @param layer - The layer ID or listener previously used to install the listener.\n * @param listener - The function previously installed as a listener.\n */\n off(\n type: T,\n layer: string,\n listener: (ev: MapLayerEventType[T] & Object) => void,\n ): this;\n /**\n * Overload of the `off` method that allows to remove an event created with multiple layers.\n * Provide the same layer IDs as to `on` or `once`, when the listener was registered.\n * @event\n * @param type - The type of the event.\n * @param layers - The layer IDs previously used to install the listener.\n * @param listener - The function previously installed as a listener.\n */\n off(\n type: T,\n layers: string[],\n listener: (ev: MapLayerEventType[T] & Object) => void,\n ): this;\n /**\n * Overload of the `off` method that allows to remove an event created without specifying a layer.\n * @event\n * @param type - The type of the event.\n * @param listener - The function previously installed as a listener.\n */\n off(type: T, listener: (ev: MapEventType[T] & Object) => void): this;\n /**\n * Overload of the `off` method that allows to remove an event created without specifying a layer.\n * @event\n * @param type - The type of the event.\n * @param listener - The function previously installed as a listener.\n */\n off(type: keyof MapEventType | string, listener: Listener): this;\n off(type: keyof MapEventType | string, layerIdsOrListener: string | string[] | Listener, listener?: Listener): this {\n if (listener === undefined) {\n return super.off(type, layerIdsOrListener as Listener);\n }\n\n const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener as string[];\n this._removeDelegatedListener(type, layerIds, listener);\n\n return this;\n }\n\n /**\n * Returns an array of MapGeoJSONFeature objects\n * representing visible features that satisfy the query parameters.\n *\n * @param geometryOrOptions - (optional) The geometry of the query region:\n * either a single point or southwest and northeast points describing a bounding box.\n * Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments,\n * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire\n * map viewport.\n * The geometryOrOptions can receive a {@link QueryRenderedFeaturesOptions} only to support a situation where the function receives only one parameter which is the options parameter.\n * @param options - (optional) Options object.\n *\n * @returns An array of MapGeoJSONFeature objects.\n *\n * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only\n * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported).\n *\n * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object\n * representing the style layer to which the feature belongs. Layout and paint properties in this object contain values\n * which are fully evaluated for the given zoom level and feature.\n *\n * Only features that are currently rendered are included. Some features will **not** be included, like:\n *\n * - Features from layers whose `visibility` property is `\"none\"`.\n * - Features from layers whose zoom range excludes the current zoom level.\n * - Symbol features that have been hidden due to text or icon collision.\n *\n * Features from all other layers are included, including features that may have no visible\n * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to\n * 0.\n *\n * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by\n * descending z-order. Features that are rendered multiple times (due to wrapping across the antemeridian at low\n * zoom levels) are returned only once (though subject to the following caveat).\n *\n * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature\n * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple\n * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.\n * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding\n * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile\n * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple\n * tiles due to tile buffering.\n *\n * @example\n * Find all features at a point\n * ```ts\n * let features = map.queryRenderedFeatures(\n * [20, 35],\n * { layers: ['my-layer-name'] }\n * );\n * ```\n *\n * @example\n * Find all features within a static bounding box\n * ```ts\n * let features = map.queryRenderedFeatures(\n * [[10, 20], [30, 50]],\n * { layers: ['my-layer-name'] }\n * );\n * ```\n *\n * @example\n * Find all features within a bounding box around a point\n * ```ts\n * let width = 10;\n * let height = 20;\n * let features = map.queryRenderedFeatures([\n * [point.x - width / 2, point.y - height / 2],\n * [point.x + width / 2, point.y + height / 2]\n * ], { layers: ['my-layer-name'] });\n * ```\n *\n * @example\n * Query all rendered features from a single layer\n * ```ts\n * let features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });\n * ```\n * @see [Get features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/queryrenderedfeatures/)\n */\n queryRenderedFeatures(geometryOrOptions?: PointLike | [PointLike, PointLike] | QueryRenderedFeaturesOptions, options?: QueryRenderedFeaturesOptions): MapGeoJSONFeature[] {\n if (!this.style) {\n return [];\n }\n let queryGeometry;\n const isGeometry = geometryOrOptions instanceof Point || Array.isArray(geometryOrOptions);\n const geometry = isGeometry ? geometryOrOptions : [[0, 0], [this.transform.width, this.transform.height]];\n options = options || (isGeometry ? {} : geometryOrOptions) || {};\n\n if (geometry instanceof Point || typeof geometry[0] === 'number') {\n queryGeometry = [Point.convert(geometry as PointLike)];\n } else {\n const tl = Point.convert(geometry[0] as PointLike);\n const br = Point.convert(geometry[1] as PointLike);\n queryGeometry = [tl, new Point(br.x, tl.y), br, new Point(tl.x, br.y), tl];\n }\n\n return this.style.queryRenderedFeatures(queryGeometry, options, this.transform);\n }\n\n /**\n * Returns an array of MapGeoJSONFeature objects\n * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.\n *\n * @param sourceId - The ID of the vector tile or GeoJSON source to query.\n * @param parameters - The options object.\n * @returns An array of MapGeoJSONFeature objects.\n *\n * In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters,\n * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded\n * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently\n * visible viewport.\n *\n * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature\n * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple\n * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.\n * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding\n * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile\n * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple\n * tiles due to tile buffering.\n *\n * @example\n * Find all features in one source layer in a vector source\n * ```ts\n * let features = map.querySourceFeatures('your-source-id', {\n * sourceLayer: 'your-source-layer'\n * });\n * ```\n *\n */\n querySourceFeatures(sourceId: string, parameters?: QuerySourceFeatureOptions | null): MapGeoJSONFeature[] {\n return this.style.querySourceFeatures(sourceId, parameters);\n }\n\n /**\n * Updates the map's MapLibre style object with a new value.\n *\n * If a style is already set when this is used and options.diff is set to true, the map renderer will attempt to compare the given style\n * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites\n * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current\n * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building\n * the given one from scratch.\n *\n *\n * @param style - A JSON object conforming to the schema described in the\n * [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/), or a URL to such JSON.\n * @param options - The options object.\n *\n * @example\n * ```ts\n * map.setStyle(\"https://demotiles.maplibre.org/style.json\");\n *\n * map.setStyle('https://demotiles.maplibre.org/style.json', {\n * transformStyle: (previousStyle, nextStyle) => ({\n * ...nextStyle,\n * sources: {\n * ...nextStyle.sources,\n * // copy a source from previous style\n * 'osm': previousStyle.sources.osm\n * },\n * layers: [\n * // background layer\n * nextStyle.layers[0],\n * // copy a layer from previous style\n * previousStyle.layers[0],\n * // other layers from the next style\n * ...nextStyle.layers.slice(1).map(layer => {\n * // hide the layers we don't need from demotiles style\n * if (layer.id.startsWith('geolines')) {\n * layer.layout = {...layer.layout || {}, visibility: 'none'};\n * // filter out US polygons\n * } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) {\n * layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA'];\n * }\n * return layer;\n * })\n * ]\n * })\n * });\n * ```\n */\n setStyle(style: StyleSpecification | string | null, options?: StyleSwapOptions & StyleOptions): this {\n options = extend({},\n {\n localIdeographFontFamily: this._localIdeographFontFamily,\n validate: this._validateStyle\n }, options);\n\n if ((options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily) && this.style && style) {\n this._diffStyle(style, options);\n return this;\n } else {\n this._localIdeographFontFamily = options.localIdeographFontFamily;\n return this._updateStyle(style, options);\n }\n }\n\n /**\n * Updates the requestManager's transform request with a new function\n *\n * @param transformRequest - A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests.\n * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties\n *\n * @example\n * ```ts\n * map.setTransformRequest((url: string, resourceType: string) => {});\n * ```\n */\n setTransformRequest(transformRequest: RequestTransformFunction): this {\n this._requestManager.setTransformRequest(transformRequest);\n return this;\n }\n\n _getUIString(key: keyof typeof defaultLocale) {\n const str = this._locale[key];\n if (str == null) {\n throw new Error(`Missing UI string '${key}'`);\n }\n\n return str;\n }\n\n _updateStyle(style: StyleSpecification | string | null, options?: StyleSwapOptions & StyleOptions) {\n // transformStyle relies on having previous style serialized, if it is not loaded yet, delay _updateStyle until previous style is loaded\n if (options.transformStyle && this.style && !this.style._loaded) {\n this.style.once('style.load', () => this._updateStyle(style, options));\n return;\n }\n\n const previousStyle = this.style && options.transformStyle ? this.style.serialize() : undefined;\n if (this.style) {\n this.style.setEventedParent(null);\n\n // Only release workers when map is getting disposed\n this.style._remove(!style);\n }\n\n if (!style) {\n delete this.style;\n return this;\n } else {\n this.style = new Style(this, options || {});\n }\n\n this.style.setEventedParent(this, {style: this.style});\n\n if (typeof style === 'string') {\n this.style.loadURL(style, options, previousStyle);\n } else {\n this.style.loadJSON(style, options, previousStyle);\n }\n\n return this;\n }\n\n _lazyInitEmptyStyle() {\n if (!this.style) {\n this.style = new Style(this, {});\n this.style.setEventedParent(this, {style: this.style});\n this.style.loadEmpty();\n }\n }\n\n _diffStyle(style: StyleSpecification | string, options?: StyleSwapOptions & StyleOptions) {\n if (typeof style === 'string') {\n const url = style;\n const request = this._requestManager.transformRequest(url, ResourceType.Style);\n getJSON(request, new AbortController()).then((response) => {\n this._updateDiff(response.data, options);\n }).catch((error) => {\n if (error) {\n this.fire(new ErrorEvent(error));\n }\n });\n } else if (typeof style === 'object') {\n this._updateDiff(style, options);\n }\n }\n\n _updateDiff(style: StyleSpecification, options?: StyleSwapOptions & StyleOptions) {\n try {\n if (this.style.setState(style, options)) {\n this._update(true);\n }\n } catch (e) {\n warnOnce(\n `Unable to perform style diff: ${e.message || e.error || e}. Rebuilding the style from scratch.`\n );\n this._updateStyle(style, options);\n }\n }\n\n /**\n * Returns the map's MapLibre style object, a JSON object which can be used to recreate the map's style.\n *\n * @returns The map's style JSON object.\n *\n * @example\n * ```ts\n * let styleJson = map.getStyle();\n * ```\n *\n */\n getStyle(): StyleSpecification {\n if (this.style) {\n return this.style.serialize();\n }\n }\n\n /**\n * Returns a Boolean indicating whether the map's style is fully loaded.\n *\n * @returns A Boolean indicating whether the style is fully loaded.\n *\n * @example\n * ```ts\n * let styleLoadStatus = map.isStyleLoaded();\n * ```\n */\n isStyleLoaded(): boolean | void {\n if (!this.style) return warnOnce('There is no style added to the map.');\n return this.style.loaded();\n }\n\n /**\n * Adds a source to the map's style.\n *\n * Events triggered:\n *\n * Triggers the `source.add` event.\n *\n * @param id - The ID of the source to add. Must not conflict with existing sources.\n * @param source - The source object, conforming to the\n * MapLibre Style Specification's [source definition](https://maplibre.org/maplibre-style-spec/sources) or\n * {@link CanvasSourceSpecification}.\n * @example\n * ```ts\n * map.addSource('my-data', {\n * type: 'vector',\n * url: 'https://demotiles.maplibre.org/tiles/tiles.json'\n * });\n * ```\n * @example\n * ```ts\n * map.addSource('my-data', {\n * \"type\": \"geojson\",\n * \"data\": {\n * \"type\": \"Feature\",\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [-77.0323, 38.9131]\n * },\n * \"properties\": {\n * \"title\": \"Mapbox DC\",\n * \"marker-symbol\": \"monument\"\n * }\n * }\n * });\n * ```\n * @see GeoJSON source: [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/)\n */\n addSource(id: string, source: SourceSpecification | CanvasSourceSpecification): this {\n this._lazyInitEmptyStyle();\n this.style.addSource(id, source);\n return this._update(true);\n }\n\n /**\n * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with\n * the given ID in the map's style has no outstanding network requests, otherwise `false`.\n *\n * A {@link ErrorEvent} event will be fired if there is no source wit the specified ID.\n *\n * @param id - The ID of the source to be checked.\n * @returns A Boolean indicating whether the source is loaded.\n * @example\n * ```ts\n * let sourceLoaded = map.isSourceLoaded('bathymetry-data');\n * ```\n */\n isSourceLoaded(id: string): boolean {\n const source = this.style && this.style.sourceCaches[id];\n if (source === undefined) {\n this.fire(new ErrorEvent(new Error(`There is no source with ID '${id}'`)));\n return;\n }\n return source.loaded();\n }\n\n /**\n * Loads a 3D terrain mesh, based on a \"raster-dem\" source.\n *\n * Triggers the `terrain` event.\n *\n * @param options - Options object.\n * @example\n * ```ts\n * map.setTerrain({ source: 'terrain' });\n * ```\n */\n setTerrain(options: TerrainSpecification | null): this {\n this.style._checkLoaded();\n\n // clear event handlers\n if (this._terrainDataCallback) this.style.off('data', this._terrainDataCallback);\n\n if (!options) {\n // remove terrain\n if (this.terrain) this.terrain.sourceCache.destruct();\n this.terrain = null;\n if (this.painter.renderToTexture) this.painter.renderToTexture.destruct();\n this.painter.renderToTexture = null;\n this.transform.minElevationForCurrentTile = 0;\n this.transform.elevation = 0;\n } else {\n // add terrain\n const sourceCache = this.style.sourceCaches[options.source];\n if (!sourceCache) throw new Error(`cannot load terrain, because there exists no source with ID: ${options.source}`);\n // Update terrain tiles when adding new terrain\n if (this.terrain === null) sourceCache.reload();\n // Warn once if user is using the same source for hillshade and terrain\n for (const index in this.style._layers) {\n const thisLayer = this.style._layers[index];\n if (thisLayer.type === 'hillshade' && thisLayer.source === options.source) {\n warnOnce('You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.');\n }\n }\n this.terrain = new Terrain(this.painter, sourceCache, options);\n this.painter.renderToTexture = new RenderToTexture(this.painter, this.terrain);\n this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom);\n this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom);\n this._terrainDataCallback = e => {\n if (e.dataType === 'style') {\n this.terrain.sourceCache.freeRtt();\n } else if (e.dataType === 'source' && e.tile) {\n if (e.sourceId === options.source && !this._elevationFreeze) {\n this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom);\n this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom);\n }\n this.terrain.sourceCache.freeRtt(e.tile.tileID);\n }\n };\n this.style.on('data', this._terrainDataCallback);\n }\n\n this.fire(new Event('terrain', {terrain: options}));\n return this;\n }\n\n /**\n * Get the terrain-options if terrain is loaded\n * @returns the TerrainSpecification passed to setTerrain\n * @example\n * ```ts\n * map.getTerrain(); // { source: 'terrain' };\n * ```\n */\n getTerrain(): TerrainSpecification | null {\n return this.terrain?.options ?? null;\n }\n\n /**\n * Returns a Boolean indicating whether all tiles in the viewport from all sources on\n * the style are loaded.\n *\n * @returns A Boolean indicating whether all tiles are loaded.\n * @example\n * ```ts\n * let tilesLoaded = map.areTilesLoaded();\n * ```\n */\n areTilesLoaded(): boolean {\n const sources = this.style && this.style.sourceCaches;\n for (const id in sources) {\n const source = sources[id];\n const tiles = source._tiles;\n for (const t in tiles) {\n const tile = tiles[t];\n if (!(tile.state === 'loaded' || tile.state === 'errored')) return false;\n }\n }\n return true;\n }\n\n /**\n * Removes a source from the map's style.\n *\n * @param id - The ID of the source to remove.\n * @example\n * ```ts\n * map.removeSource('bathymetry-data');\n * ```\n */\n removeSource(id: string): Map {\n this.style.removeSource(id);\n return this._update(true);\n }\n\n /**\n * Returns the source with the specified ID in the map's style.\n *\n * This method is often used to update a source using the instance members for the relevant\n * source type as defined in classes that derive from {@link Source}.\n * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates`\n * of an image source.\n *\n * @param id - The ID of the source to get.\n * @returns The style source with the specified ID or `undefined` if the ID\n * corresponds to no existing sources.\n * The shape of the object varies by source type.\n * A list of options for each source type is available on the MapLibre Style Specification's\n * [Sources](https://maplibre.org/maplibre-style-spec/sources/) page.\n * @example\n * ```ts\n * let sourceObject = map.getSource('points');\n * ```\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-point-along-line/)\n * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/)\n */\n getSource(id: string): TSource | undefined {\n return this.style.getSource(id) as TSource;\n }\n\n /**\n * Add an image to the style. This image can be displayed on the map like any other icon in the style's\n * sprite using the image's ID with\n * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image),\n * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern),\n * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern),\n * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern).\n *\n * A {@link ErrorEvent} event will be fired if the image parameter is invalid or there is not enough space in the sprite to add this image.\n *\n * @param id - The ID of the image.\n * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`\n * properties with the same format as `ImageData`.\n * @param options - Options object.\n * @example\n * ```ts\n * // If the style's sprite does not already contain an image with ID 'cat',\n * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'.\n * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png');\n * if (!map.hasImage('cat')) map.addImage('cat', image.data);\n *\n * // Add a stretchable image that can be used with `icon-text-fit`\n * // In this example, the image is 600px wide by 400px high.\n * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png');\n * if (map.hasImage('border-image')) return;\n * map.addImage('border-image', image.data, {\n * content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border\n * stretchX: [[16, 584]], // stretch everything horizontally except the 16px border\n * stretchY: [[16, 384]], // stretch everything vertically except the 16px border\n * });\n * ```\n * @see Use `HTMLImageElement`: [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/)\n * @see Use `ImageData`: [Add a generated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-generated/)\n */\n addImage(id: string,\n image: HTMLImageElement | ImageBitmap | ImageData | {\n width: number;\n height: number;\n data: Uint8Array | Uint8ClampedArray;\n } | StyleImageInterface,\n options: Partial = {}): this {\n const {\n pixelRatio = 1,\n sdf = false,\n stretchX,\n stretchY,\n content,\n textFitWidth,\n textFitHeight\n } = options;\n this._lazyInitEmptyStyle();\n const version = 0;\n\n if (image instanceof HTMLImageElement || isImageBitmap(image)) {\n const {width, height, data} = browser.getImageData(image);\n this.style.addImage(id, {data: new RGBAImage({width, height}, data), pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight, sdf, version});\n } else if (image.width === undefined || image.height === undefined) {\n return this.fire(new ErrorEvent(new Error(\n 'Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' +\n 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));\n } else {\n const {width, height, data} = image as ImageData;\n const userImage = (image as any as StyleImageInterface);\n\n this.style.addImage(id, {\n data: new RGBAImage({width, height}, new Uint8Array(data)),\n pixelRatio,\n stretchX,\n stretchY,\n content,\n textFitWidth,\n textFitHeight,\n sdf,\n version,\n userImage\n });\n\n if (userImage.onAdd) {\n userImage.onAdd(this, id);\n }\n return this;\n }\n }\n\n /**\n * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's\n * sprite using the image's ID with\n * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image),\n * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern),\n * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern),\n * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern).\n *\n * An {@link ErrorEvent} will be fired if the image parameter is invald.\n *\n * @param id - The ID of the image.\n * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`\n * properties with the same format as `ImageData`.\n * @example\n * ```ts\n * // If an image with the ID 'cat' already exists in the style's sprite,\n * // replace that image with a new image, 'other-cat-icon.png'.\n * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png');\n * ```\n */\n updateImage(id: string,\n image: HTMLImageElement | ImageBitmap | ImageData | {\n width: number;\n height: number;\n data: Uint8Array | Uint8ClampedArray;\n } | StyleImageInterface): this {\n\n const existingImage = this.style.getImage(id);\n if (!existingImage) {\n return this.fire(new ErrorEvent(new Error(\n 'The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.')));\n }\n const imageData = (image instanceof HTMLImageElement || isImageBitmap(image)) ?\n browser.getImageData(image) :\n image;\n const {width, height, data} = imageData;\n\n if (width === undefined || height === undefined) {\n return this.fire(new ErrorEvent(new Error(\n 'Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' +\n 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));\n }\n\n if (width !== existingImage.data.width || height !== existingImage.data.height) {\n return this.fire(new ErrorEvent(new Error(\n 'The width and height of the updated image must be that same as the previous version of the image')));\n }\n\n const copy = !(image instanceof HTMLImageElement || isImageBitmap(image));\n existingImage.data.replace(data, copy);\n\n this.style.updateImage(id, existingImage);\n return this;\n }\n\n /**\n * Returns an image, specified by ID, currently available in the map.\n * This includes both images from the style's original sprite\n * and any images that have been added at runtime using {@link Map#addImage}.\n *\n * @param id - The ID of the image.\n * @returns An image in the map with the specified ID.\n *\n * @example\n * ```ts\n * let coffeeShopIcon = map.getImage(\"coffee_cup\");\n * ```\n */\n getImage(id: string): StyleImage {\n return this.style.getImage(id);\n }\n\n /**\n * Check whether or not an image with a specific ID exists in the style. This checks both images\n * in the style's original sprite and any images\n * that have been added at runtime using {@link Map#addImage}.\n *\n * An {@link ErrorEvent} will be fired if the image parameter is invald.\n *\n * @param id - The ID of the image.\n *\n * @returns A Boolean indicating whether the image exists.\n * @example\n * Check if an image with the ID 'cat' exists in the style's sprite.\n * ```ts\n * let catIconExists = map.hasImage('cat');\n * ```\n */\n hasImage(id: string): boolean {\n if (!id) {\n this.fire(new ErrorEvent(new Error('Missing required image id')));\n return false;\n }\n\n return !!this.style.getImage(id);\n }\n\n /**\n * Remove an image from a style. This can be an image from the style's original\n * sprite or any images\n * that have been added at runtime using {@link Map#addImage}.\n *\n * @param id - The ID of the image.\n *\n * @example\n * ```ts\n * // If an image with the ID 'cat' exists in\n * // the style's sprite, remove it.\n * if (map.hasImage('cat')) map.removeImage('cat');\n * ```\n */\n removeImage(id: string) {\n this.style.removeImage(id);\n }\n\n /**\n * Load an image from an external URL to be used with {@link Map#addImage}. External\n * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).\n *\n * @param url - The URL of the image file. Image file must be in png, webp, or jpg format.\n * @returns a promise that is resolved when the image is loaded\n *\n * @example\n * Load an image from an external URL.\n * ```ts\n * const response = await map.loadImage('https://picsum.photos/50/50');\n * // Add the loaded image to the style's sprite with the ID 'photo'.\n * map.addImage('photo', response.data);\n * ```\n * @see [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/)\n */\n loadImage(url: string): Promise> {\n return ImageRequest.getImage(this._requestManager.transformRequest(url, ResourceType.Image), new AbortController());\n }\n\n /**\n * Returns an Array of strings containing the IDs of all images currently available in the map.\n * This includes both images from the style's original sprite\n * and any images that have been added at runtime using {@link Map#addImage}.\n *\n * @returns An Array of strings containing the names of all sprites/images currently available in the map.\n *\n * @example\n * ```ts\n * let allImages = map.listImages();\n * ```\n */\n listImages(): Array {\n return this.style.listImages();\n }\n\n /**\n * Adds a [MapLibre style layer](https://maplibre.org/maplibre-style-spec/layers)\n * to the map's style.\n *\n * A layer defines how data from a specified source will be styled. Read more about layer types\n * and available paint and layout properties in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/layers).\n *\n * @param layer - The layer to add,\n * conforming to either the MapLibre Style Specification's [layer definition](https://maplibre.org/maplibre-style-spec/layers) or,\n * less commonly, the {@link CustomLayerInterface} specification. Can also be a layer definition with an embedded source definition.\n * The MapLibre Style Specification's layer definition is appropriate for most layers.\n *\n * @param beforeId - The ID of an existing layer to insert the new layer before,\n * resulting in the new layer appearing visually beneath the existing layer.\n * If this argument is not specified, the layer will be appended to the end of the layers array\n * and appear visually above all other layers.\n *\n * @example\n * Add a circle layer with a vector source\n * ```ts\n * map.addLayer({\n * id: 'points-of-interest',\n * source: {\n * type: 'vector',\n * url: 'https://demotiles.maplibre.org/tiles/tiles.json'\n * },\n * 'source-layer': 'poi_label',\n * type: 'circle',\n * paint: {\n * // MapLibre Style Specification paint properties\n * },\n * layout: {\n * // MapLibre Style Specification layout properties\n * }\n * });\n * ```\n *\n * @example\n * Define a source before using it to create a new layer\n * ```ts\n * map.addSource('state-data', {\n * type: 'geojson',\n * data: 'path/to/data.geojson'\n * });\n *\n * map.addLayer({\n * id: 'states',\n * // References the GeoJSON source defined above\n * // and does not require a `source-layer`\n * source: 'state-data',\n * type: 'symbol',\n * layout: {\n * // Set the label content to the\n * // feature's `name` property\n * text-field: ['get', 'name']\n * }\n * });\n * ```\n *\n * @example\n * Add a new symbol layer before an existing layer\n * ```ts\n * map.addLayer({\n * id: 'states',\n * // References a source that's already been defined\n * source: 'state-data',\n * type: 'symbol',\n * layout: {\n * // Set the label content to the\n * // feature's `name` property\n * text-field: ['get', 'name']\n * }\n * // Add the layer before the existing `cities` layer\n * }, 'cities');\n * ```\n * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/)\n * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/)\n * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/)\n */\n addLayer(layer: AddLayerObject, beforeId?: string) {\n this._lazyInitEmptyStyle();\n this.style.addLayer(layer, beforeId);\n return this._update(true);\n }\n\n /**\n * Moves a layer to a different z-position.\n *\n * @param id - The ID of the layer to move.\n * @param beforeId - The ID of an existing layer to insert the new layer before. When viewing the map, the `id` layer will appear beneath the `beforeId` layer. If `beforeId` is omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map.\n *\n * @example\n * Move a layer with ID 'polygon' before the layer with ID 'country-label'. The `polygon` layer will appear beneath the `country-label` layer on the map.\n * ```ts\n * map.moveLayer('polygon', 'country-label');\n * ```\n */\n moveLayer(id: string, beforeId?: string): this {\n this.style.moveLayer(id, beforeId);\n return this._update(true);\n }\n\n /**\n * Removes the layer with the given ID from the map's style.\n *\n * An {@link ErrorEvent} will be fired if the image parameter is invald.\n *\n * @param id - The ID of the layer to remove\n *\n * @example\n * If a layer with ID 'state-data' exists, remove it.\n * ```ts\n * if (map.getLayer('state-data')) map.removeLayer('state-data');\n * ```\n */\n removeLayer(id: string): this {\n this.style.removeLayer(id);\n return this._update(true);\n }\n\n /**\n * Returns the layer with the specified ID in the map's style.\n *\n * @param id - The ID of the layer to get.\n * @returns The layer with the specified ID, or `undefined`\n * if the ID corresponds to no existing layers.\n *\n * @example\n * ```ts\n * let stateDataLayer = map.getLayer('state-data');\n * ```\n * @see [Filter symbols by toggling a list](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers/)\n * @see [Filter symbols by text input](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers-by-input/)\n */\n getLayer(id: string): StyleLayer | undefined {\n return this.style.getLayer(id);\n }\n\n /**\n * Return the ids of all layers currently in the style, including custom layers, in order.\n *\n * @returns ids of layers, in order\n *\n * @example\n * ```ts\n * const orderedLayerIds = map.getLayersOrder();\n * ```\n */\n getLayersOrder(): string[] {\n return this.style.getLayersOrder();\n }\n\n /**\n * Sets the zoom extent for the specified style layer. The zoom extent includes the\n * [minimum zoom level](https://maplibre.org/maplibre-style-spec/layers/#minzoom)\n * and [maximum zoom level](https://maplibre.org/maplibre-style-spec/layers/#maxzoom))\n * at which the layer will be rendered.\n *\n * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the\n * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum\n * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style\n * layer will not be rendered at all zoom levels in the zoom range.\n *\n * @param layerId - The ID of the layer to which the zoom extent will be applied.\n * @param minzoom - The minimum zoom to set (0-24).\n * @param maxzoom - The maximum zoom to set (0-24).\n *\n * @example\n * ```ts\n * map.setLayerZoomRange('my-layer', 2, 5);\n * ```\n */\n setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this {\n this.style.setLayerZoomRange(layerId, minzoom, maxzoom);\n return this._update(true);\n }\n\n /**\n * Sets the filter for the specified style layer.\n *\n * Filters control which features a style layer renders from its source.\n * Any feature for which the filter expression evaluates to `true` will be\n * rendered on the map. Those that are false will be hidden.\n *\n * Use `setFilter` to show a subset of your source data.\n *\n * To clear the filter, pass `null` or `undefined` as the second parameter.\n *\n * @param layerId - The ID of the layer to which the filter will be applied.\n * @param filter - The filter, conforming to the MapLibre Style Specification's\n * [filter definition](https://maplibre.org/maplibre-style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer.\n * @param options - Options object.\n *\n * @example\n * Display only features with the 'name' property 'USA'\n * ```ts\n * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']);\n * ```\n * @example\n * Display only features with five or more 'available-spots'\n * ```ts\n * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]);\n * ```\n * @example\n * Remove the filter for the 'bike-docks' style layer\n * ```ts\n * map.setFilter('bike-docks', null);\n * ```\n * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/)\n */\n setFilter(layerId: string, filter?: FilterSpecification | null, options: StyleSetterOptions = {}) {\n this.style.setFilter(layerId, filter, options);\n return this._update(true);\n }\n\n /**\n * Returns the filter applied to the specified style layer.\n *\n * @param layerId - The ID of the style layer whose filter to get.\n * @returns The layer's filter.\n */\n getFilter(layerId: string): FilterSpecification | void {\n return this.style.getFilter(layerId);\n }\n\n /**\n * Sets the value of a paint property in the specified style layer.\n *\n * @param layerId - The ID of the layer to set the paint property in.\n * @param name - The name of the paint property to set.\n * @param value - The value of the paint property to set.\n * Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/).\n * Pass `null` to unset the existing value.\n * @param options - Options object.\n * @example\n * ```ts\n * map.setPaintProperty('my-layer', 'fill-color', '#faafee');\n * ```\n * @see [Change a layer's color with buttons](https://maplibre.org/maplibre-gl-js/docs/examples/color-switcher/)\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}): this {\n this.style.setPaintProperty(layerId, name, value, options);\n return this._update(true);\n }\n\n /**\n * Returns the value of a paint property in the specified style layer.\n *\n * @param layerId - The ID of the layer to get the paint property from.\n * @param name - The name of a paint property to get.\n * @returns The value of the specified paint property.\n */\n getPaintProperty(layerId: string, name: string) {\n return this.style.getPaintProperty(layerId, name);\n }\n\n /**\n * Sets the value of a layout property in the specified style layer.\n *\n * @param layerId - The ID of the layer to set the layout property in.\n * @param name - The name of the layout property to set.\n * @param value - The value of the layout property. Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/).\n * @param options - The options object.\n * @example\n * ```ts\n * map.setLayoutProperty('my-layer', 'visibility', 'none');\n * ```\n */\n setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}): this {\n this.style.setLayoutProperty(layerId, name, value, options);\n return this._update(true);\n }\n\n /**\n * Returns the value of a layout property in the specified style layer.\n *\n * @param layerId - The ID of the layer to get the layout property from.\n * @param name - The name of the layout property to get.\n * @returns The value of the specified layout property.\n */\n getLayoutProperty(layerId: string, name: string) {\n return this.style.getLayoutProperty(layerId, name);\n }\n\n /**\n * Sets the value of the style's glyphs property.\n *\n * @param glyphsUrl - Glyph URL to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/glyphs/).\n * @param options - Options object.\n * @example\n * ```ts\n * map.setGlyphs('https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf');\n * ```\n */\n setGlyphs(glyphsUrl: string | null, options: StyleSetterOptions = {}): this {\n this._lazyInitEmptyStyle();\n this.style.setGlyphs(glyphsUrl, options);\n return this._update(true);\n }\n\n /**\n * Returns the value of the style's glyphs URL\n *\n * @returns glyphs Style's glyphs url\n */\n getGlyphs(): string | null {\n return this.style.getGlyphsUrl();\n }\n\n /**\n * Adds a sprite to the map's style. Fires the `style` event.\n *\n * @param id - The ID of the sprite to add. Must not conflict with existing sprites.\n * @param url - The URL to load the sprite from\n * @param options - Options object.\n * @example\n * ```ts\n * map.addSprite('sprite-two', 'http://example.com/sprite-two');\n * ```\n */\n addSprite(id: string, url: string, options: StyleSetterOptions = {}): this {\n this._lazyInitEmptyStyle();\n this.style.addSprite(id, url, options, (err) => {\n if (!err) {\n this._update(true);\n }\n });\n return this;\n }\n\n /**\n * Removes the sprite from the map's style. Fires the `style` event.\n *\n * @param id - The ID of the sprite to remove. If the sprite is declared as a single URL, the ID must be \"default\".\n * @example\n * ```ts\n * map.removeSprite('sprite-two');\n * map.removeSprite('default');\n * ```\n */\n removeSprite(id: string) {\n this._lazyInitEmptyStyle();\n this.style.removeSprite(id);\n return this._update(true);\n }\n\n /**\n * Returns the as-is value of the style's sprite.\n *\n * @returns style's sprite list of id-url pairs\n */\n getSprite(): {id: string; url: string}[] {\n return this.style.getSprite();\n }\n\n /**\n * Sets the value of the style's sprite property.\n *\n * @param spriteUrl - Sprite URL to set.\n * @param options - Options object.\n * @example\n * ```ts\n * map.setSprite('YOUR_SPRITE_URL');\n * ```\n */\n setSprite(spriteUrl: string | null, options: StyleSetterOptions = {}) {\n this._lazyInitEmptyStyle();\n this.style.setSprite(spriteUrl, options, (err) => {\n if (!err) {\n this._update(true);\n }\n });\n return this;\n }\n\n /**\n * Sets the any combination of light values.\n *\n * @param light - Light properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/light).\n * @param options - Options object.\n *\n * @example\n * ```ts\n * let layerVisibility = map.getLayoutProperty('my-layer', 'visibility');\n * ```\n */\n setLight(light: LightSpecification, options: StyleSetterOptions = {}) {\n this._lazyInitEmptyStyle();\n this.style.setLight(light, options);\n return this._update(true);\n }\n\n /**\n * Returns the value of the light object.\n *\n * @returns light Light properties of the style.\n */\n getLight(): LightSpecification {\n return this.style.getLight();\n }\n\n /**\n * Loads sky and fog defined by {@link SkySpecification} onto the map.\n * Note: The fog only shows when using the terrain 3D feature.\n * @param sky - Sky properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/sky/).\n * @returns `this`\n * @example\n * ```ts\n * map.setSky({ 'sky-color': '#00f' });\n * ```\n */\n setSky(sky: SkySpecification) {\n this._lazyInitEmptyStyle();\n this.style.setSky(sky);\n return this._update(true);\n }\n\n /**\n * Returns the value of the sky object.\n *\n * @returns the sky properties of the style.\n * @example\n * ```ts\n * map.getSky();\n * ```\n */\n getSky() {\n return this.style.getSky();\n }\n\n /**\n * Sets the `state` of a feature.\n * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.\n * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state.\n * Features are identified by their `feature.id` attribute, which can be any number or string.\n *\n * This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways:\n *\n * - For vector or GeoJSON sources, including an `id` attribute in the original data file.\n * - For vector or GeoJSON sources, using the [`promoteId`](https://maplibre.org/maplibre-style-spec/sources/#vector-promoteId) option at the time the source is defined.\n * - For GeoJSON sources, using the [`generateId`](https://maplibre.org/maplibre-style-spec/sources/#geojson-generateId) option to auto-assign an `id` based on the feature's index in the source data. If you change feature data using `map.getSource('some id').setData(..)`, you may need to re-apply state taking into account updated `id` values.\n *\n * _Note: You can use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling._\n *\n * @param feature - Feature identifier. Feature objects returned from\n * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.\n * @param state - A set of key-value pairs. The values should be valid JSON types.\n *\n * @example\n * ```ts\n * // When the mouse moves over the `my-layer` layer, update\n * // the feature state for the feature under the mouse\n * map.on('mousemove', 'my-layer', (e) => {\n * if (e.features.length > 0) {\n * map.setFeatureState({\n * source: 'my-source',\n * sourceLayer: 'my-source-layer',\n * id: e.features[0].id,\n * }, {\n * hover: true\n * });\n * }\n * });\n * ```\n * @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/)\n */\n setFeatureState(feature: FeatureIdentifier, state: any): this {\n this.style.setFeatureState(feature, state);\n return this._update();\n }\n\n /**\n * Removes the `state` of a feature, setting it back to the default behavior.\n * If only a `target.source` is specified, it will remove the state for all features from that source.\n * If `target.id` is also specified, it will remove all keys for that feature's state.\n * If `key` is also specified, it removes only that key from that feature's state.\n * Features are identified by their `feature.id` attribute, which can be any number or string.\n *\n * @param target - Identifier of where to remove state. It can be a source, a feature, or a specific key of feature.\n * Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.\n * @param key - (optional) The key in the feature state to reset.\n * @example\n * Reset the entire state object for all features in the `my-source` source\n * ```ts\n * map.removeFeatureState({\n * source: 'my-source'\n * });\n * ```\n *\n * @example\n * When the mouse leaves the `my-layer` layer,\n * reset the entire state object for the\n * feature under the mouse\n * ```ts\n * map.on('mouseleave', 'my-layer', (e) => {\n * map.removeFeatureState({\n * source: 'my-source',\n * sourceLayer: 'my-source-layer',\n * id: e.features[0].id\n * });\n * });\n * ```\n *\n * @example\n * When the mouse leaves the `my-layer` layer,\n * reset only the `hover` key-value pair in the\n * state for the feature under the mouse\n * ```ts\n * map.on('mouseleave', 'my-layer', (e) => {\n * map.removeFeatureState({\n * source: 'my-source',\n * sourceLayer: 'my-source-layer',\n * id: e.features[0].id\n * }, 'hover');\n * });\n * ```\n */\n removeFeatureState(target: FeatureIdentifier, key?: string): this {\n this.style.removeFeatureState(target, key);\n return this._update();\n }\n\n /**\n * Gets the `state` of a feature.\n * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.\n * Features are identified by their `feature.id` attribute, which can be any number or string.\n *\n * _Note: To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state)._\n *\n * @param feature - Feature identifier. Feature objects returned from\n * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.\n * @returns The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.\n *\n * @example\n * When the mouse moves over the `my-layer` layer,\n * get the feature state for the feature under the mouse\n * ```ts\n * map.on('mousemove', 'my-layer', (e) => {\n * if (e.features.length > 0) {\n * map.getFeatureState({\n * source: 'my-source',\n * sourceLayer: 'my-source-layer',\n * id: e.features[0].id\n * });\n * }\n * });\n * ```\n */\n getFeatureState(feature: FeatureIdentifier): any {\n return this.style.getFeatureState(feature);\n }\n\n /**\n * Returns the map's containing HTML element.\n *\n * @returns The map's container.\n */\n getContainer(): HTMLElement {\n return this._container;\n }\n\n /**\n * Returns the HTML element containing the map's `` element.\n *\n * If you want to add non-GL overlays to the map, you should append them to this element.\n *\n * This is the element to which event bindings for map interactivity (such as panning and zooming) are\n * attached. It will receive bubbled events from child elements such as the ``, but not from\n * map controls.\n *\n * @returns The container of the map's ``.\n * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/)\n */\n getCanvasContainer(): HTMLElement {\n return this._canvasContainer;\n }\n\n /**\n * Returns the map's `` element.\n *\n * @returns The map's `` element.\n * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure/)\n * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/)\n * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/)\n */\n getCanvas(): HTMLCanvasElement {\n return this._canvas;\n }\n\n _containerDimensions() {\n let width = 0;\n let height = 0;\n\n if (this._container) {\n width = this._container.clientWidth || 400;\n height = this._container.clientHeight || 300;\n }\n\n return [width, height];\n }\n\n _setupContainer() {\n const container = this._container;\n container.classList.add('maplibregl-map');\n\n const canvasContainer = this._canvasContainer = DOM.create('div', 'maplibregl-canvas-container', container);\n if (this._interactive) {\n canvasContainer.classList.add('maplibregl-interactive');\n }\n\n this._canvas = DOM.create('canvas', 'maplibregl-canvas', canvasContainer);\n this._canvas.addEventListener('webglcontextlost', this._contextLost, false);\n this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false);\n this._canvas.setAttribute('tabindex', this._interactive ? '0' : '-1');\n this._canvas.setAttribute('aria-label', this._getUIString('Map.Title'));\n this._canvas.setAttribute('role', 'region');\n\n const dimensions = this._containerDimensions();\n const clampedPixelRatio = this._getClampedPixelRatio(dimensions[0], dimensions[1]);\n this._resizeCanvas(dimensions[0], dimensions[1], clampedPixelRatio);\n\n const controlContainer = this._controlContainer = DOM.create('div', 'maplibregl-control-container', container);\n const positions = this._controlPositions = {};\n ['top-left', 'top-right', 'bottom-left', 'bottom-right'].forEach((positionName) => {\n positions[positionName] = DOM.create('div', `maplibregl-ctrl-${positionName} `, controlContainer);\n });\n\n this._container.addEventListener('scroll', this._onMapScroll, false);\n }\n\n _resizeCanvas(width: number, height: number, pixelRatio: number) {\n // Request the required canvas size taking the pixelratio into account.\n this._canvas.width = Math.floor(pixelRatio * width);\n this._canvas.height = Math.floor(pixelRatio * height);\n\n // Maintain the same canvas size, potentially downscaling it for HiDPI displays\n this._canvas.style.width = `${width}px`;\n this._canvas.style.height = `${height}px`;\n }\n\n _setupPainter() {\n\n const attributes = {\n alpha: true,\n stencil: true,\n depth: true,\n failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat,\n preserveDrawingBuffer: this._preserveDrawingBuffer,\n antialias: this._antialias || false\n };\n\n let webglcontextcreationerrorDetailObject: any = null;\n this._canvas.addEventListener('webglcontextcreationerror', (args: WebGLContextEvent) => {\n webglcontextcreationerrorDetailObject = {requestedAttributes: attributes};\n if (args) {\n webglcontextcreationerrorDetailObject.statusMessage = args.statusMessage;\n webglcontextcreationerrorDetailObject.type = args.type;\n }\n }, {once: true});\n\n const gl =\n this._canvas.getContext('webgl2', attributes) as WebGL2RenderingContext ||\n this._canvas.getContext('webgl', attributes) as WebGLRenderingContext;\n\n if (!gl) {\n const msg = 'Failed to initialize WebGL';\n if (webglcontextcreationerrorDetailObject) {\n webglcontextcreationerrorDetailObject.message = msg;\n throw new Error(JSON.stringify(webglcontextcreationerrorDetailObject));\n } else {\n throw new Error(msg);\n }\n }\n\n this.painter = new Painter(gl, this.transform);\n\n webpSupported.testSupport(gl);\n }\n\n _contextLost = (event: any) => {\n event.preventDefault();\n if (this._frameRequest) {\n this._frameRequest.abort();\n this._frameRequest = null;\n }\n this.fire(new Event('webglcontextlost', {originalEvent: event}));\n };\n\n _contextRestored = (event: any) => {\n this._setupPainter();\n this.resize();\n this._update();\n this.fire(new Event('webglcontextrestored', {originalEvent: event}));\n };\n\n _onMapScroll = (event: any) => {\n if (event.target !== this._container) return;\n\n // Revert any scroll which would move the canvas outside of the view\n this._container.scrollTop = 0;\n this._container.scrollLeft = 0;\n return false;\n };\n\n /**\n * Returns a Boolean indicating whether the map is fully loaded.\n *\n * Returns `false` if the style is not yet fully loaded,\n * or if there has been a change to the sources or style that\n * has not yet fully loaded.\n *\n * @returns A Boolean indicating whether the map is fully loaded.\n */\n loaded(): boolean {\n return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded();\n }\n\n /**\n * @internal\n * Update this map's style and sources, and re-render the map.\n *\n * @param updateStyle - mark the map's style for reprocessing as\n * well as its sources\n */\n _update(updateStyle?: boolean) {\n if (!this.style || !this.style._loaded) return this;\n\n this._styleDirty = this._styleDirty || updateStyle;\n this._sourcesDirty = true;\n this.triggerRepaint();\n\n return this;\n }\n\n /**\n * @internal\n * Request that the given callback be executed during the next render\n * frame. Schedule a render frame if one is not already scheduled.\n *\n * @returns An id that can be used to cancel the callback\n */\n _requestRenderFrame(callback: () => void): TaskID {\n this._update();\n return this._renderTaskQueue.add(callback);\n }\n\n _cancelRenderFrame(id: TaskID) {\n this._renderTaskQueue.remove(id);\n }\n\n /**\n * @internal\n * Call when a (re-)render of the map is required:\n *\n * - The style has changed (`setPaintProperty()`, etc.)\n * - Source data has changed (e.g. tiles have finished loading)\n * - The map has is moving (or just finished moving)\n * - A transition is in progress\n *\n * @param paintStartTimeStamp - The time when the animation frame began executing.\n */\n _render(paintStartTimeStamp: number) {\n const fadeDuration = this._idleTriggered ? this._fadeDuration : 0;\n\n // A custom layer may have used the context asynchronously. Mark the state as dirty.\n this.painter.context.setDirty();\n this.painter.setBaseState();\n\n this._renderTaskQueue.run(paintStartTimeStamp);\n // A task queue callback may have fired a user event which may have removed the map\n if (this._removed) return;\n\n let crossFading = false;\n\n // If the style has changed, the map is being zoomed, or a transition or fade is in progress:\n // - Apply style changes (in a batch)\n // - Recalculate paint properties.\n if (this.style && this._styleDirty) {\n this._styleDirty = false;\n\n const zoom = this.transform.zoom;\n const now = browser.now();\n this.style.zoomHistory.update(zoom, now);\n\n const parameters = new EvaluationParameters(zoom, {\n now,\n fadeDuration,\n zoomHistory: this.style.zoomHistory,\n transition: this.style.getTransition()\n });\n\n const factor = parameters.crossFadingFactor();\n if (factor !== 1 || factor !== this._crossFadingFactor) {\n crossFading = true;\n this._crossFadingFactor = factor;\n }\n\n this.style.update(parameters);\n }\n\n // If we are in _render for any reason other than an in-progress paint\n // transition, update source caches to check for and load any tiles we\n // need for the current transform\n if (this.style && this._sourcesDirty) {\n this._sourcesDirty = false;\n this.style._updateSources(this.transform);\n }\n\n // update terrain stuff\n if (this.terrain) {\n this.terrain.sourceCache.update(this.transform, this.terrain);\n this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom);\n if (!this._elevationFreeze) {\n this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom);\n }\n } else {\n this.transform.minElevationForCurrentTile = 0;\n this.transform.elevation = 0;\n }\n\n this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions);\n\n // Actually draw\n this.painter.render(this.style, {\n showTileBoundaries: this.showTileBoundaries,\n showOverdrawInspector: this._showOverdrawInspector,\n rotating: this.isRotating(),\n zooming: this.isZooming(),\n moving: this.isMoving(),\n fadeDuration,\n showPadding: this.showPadding,\n });\n\n this.fire(new Event('render'));\n\n if (this.loaded() && !this._loaded) {\n this._loaded = true;\n PerformanceUtils.mark(PerformanceMarkers.load);\n this.fire(new Event('load'));\n }\n\n if (this.style && (this.style.hasTransitions() || crossFading)) {\n this._styleDirty = true;\n }\n\n if (this.style && !this._placementDirty) {\n // Since no fade operations are in progress, we can release\n // all tiles held for fading. If we didn't do this, the tiles\n // would just sit in the SourceCaches until the next render\n this.style._releaseSymbolFadeTiles();\n }\n\n // Schedule another render frame if it's needed.\n //\n // Even though `_styleDirty` and `_sourcesDirty` are reset in this\n // method, synchronous events fired during Style#update or\n // Style#_updateSources could have caused them to be set again.\n const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty;\n if (somethingDirty || this._repaint) {\n this.triggerRepaint();\n } else if (!this.isMoving() && this.loaded()) {\n this.fire(new Event('idle'));\n }\n\n if (this._loaded && !this._fullyLoaded && !somethingDirty) {\n this._fullyLoaded = true;\n PerformanceUtils.mark(PerformanceMarkers.fullLoad);\n }\n\n return this;\n }\n\n /**\n * Force a synchronous redraw of the map.\n * @example\n * ```ts\n * map.redraw();\n * ```\n */\n redraw(): this {\n if (this.style) {\n // cancel the scheduled update\n if (this._frameRequest) {\n this._frameRequest.abort();\n this._frameRequest = null;\n }\n this._render(0);\n }\n return this;\n }\n\n /**\n * Clean up and release all internal resources associated with this map.\n *\n * This includes DOM elements, event bindings, web workers, and WebGL resources.\n *\n * Use this method when you are done using the map and wish to ensure that it no\n * longer consumes browser resources. Afterwards, you must not call any other\n * methods on the map.\n */\n remove() {\n if (this._hash) this._hash.remove();\n\n for (const control of this._controls) control.onRemove(this);\n this._controls = [];\n\n if (this._frameRequest) {\n this._frameRequest.abort();\n this._frameRequest = null;\n }\n this._renderTaskQueue.clear();\n this.painter.destroy();\n this.handlers.destroy();\n delete this.handlers;\n this.setStyle(null);\n if (typeof window !== 'undefined') {\n removeEventListener('online', this._onWindowOnline, false);\n }\n\n ImageRequest.removeThrottleControl(this._imageQueueHandle);\n\n this._resizeObserver?.disconnect();\n const extension = this.painter.context.gl.getExtension('WEBGL_lose_context');\n if (extension?.loseContext) extension.loseContext();\n this._canvas.removeEventListener('webglcontextrestored', this._contextRestored, false);\n this._canvas.removeEventListener('webglcontextlost', this._contextLost, false);\n DOM.remove(this._canvasContainer);\n DOM.remove(this._controlContainer);\n this._container.classList.remove('maplibregl-map');\n\n PerformanceUtils.clearMetrics();\n\n this._removed = true;\n this.fire(new Event('remove'));\n }\n\n /**\n * Trigger the rendering of a single frame. Use this method with custom layers to\n * repaint the map when the layer changes. Calling this multiple times before the\n * next frame is rendered will still result in only a single frame being rendered.\n * @example\n * ```ts\n * map.triggerRepaint();\n * ```\n * @see [Add a 3D model](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model/)\n * @see [Add an animated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-animated/)\n */\n triggerRepaint() {\n if (this.style && !this._frameRequest) {\n this._frameRequest = new AbortController();\n browser.frameAsync(this._frameRequest).then((paintStartTimeStamp: number) => {\n PerformanceUtils.frame(paintStartTimeStamp);\n this._frameRequest = null;\n this._render(paintStartTimeStamp);\n }).catch(() => {}); // ignore abort error\n }\n }\n\n _onWindowOnline = () => {\n this._update();\n };\n\n /**\n * Gets and sets a Boolean indicating whether the map will render an outline\n * around each tile and the tile ID. These tile boundaries are useful for\n * debugging.\n *\n * The uncompressed file size of the first vector source is drawn in the top left\n * corner of each tile, next to the tile ID.\n *\n * @example\n * ```ts\n * map.showTileBoundaries = true;\n * ```\n */\n get showTileBoundaries(): boolean { return !!this._showTileBoundaries; }\n set showTileBoundaries(value: boolean) {\n if (this._showTileBoundaries === value) return;\n this._showTileBoundaries = value;\n this._update();\n }\n\n /**\n * Gets and sets a Boolean indicating whether the map will visualize\n * the padding offsets.\n */\n get showPadding(): boolean { return !!this._showPadding; }\n set showPadding(value: boolean) {\n if (this._showPadding === value) return;\n this._showPadding = value;\n this._update();\n }\n\n /**\n * Gets and sets a Boolean indicating whether the map will render boxes\n * around all symbols in the data source, revealing which symbols\n * were rendered or which were hidden due to collisions.\n * This information is useful for debugging.\n */\n get showCollisionBoxes(): boolean { return !!this._showCollisionBoxes; }\n set showCollisionBoxes(value: boolean) {\n if (this._showCollisionBoxes === value) return;\n this._showCollisionBoxes = value;\n if (value) {\n // When we turn collision boxes on we have to generate them for existing tiles\n // When we turn them off, there's no cost to leaving existing boxes in place\n this.style._generateCollisionBoxes();\n } else {\n // Otherwise, call an update to remove collision boxes\n this._update();\n }\n }\n\n /**\n * Gets and sets a Boolean indicating whether the map should color-code\n * each fragment to show how many times it has been shaded.\n * White fragments have been shaded 8 or more times.\n * Black fragments have been shaded 0 times.\n * This information is useful for debugging.\n */\n get showOverdrawInspector(): boolean { return !!this._showOverdrawInspector; }\n set showOverdrawInspector(value: boolean) {\n if (this._showOverdrawInspector === value) return;\n this._showOverdrawInspector = value;\n this._update();\n }\n\n /**\n * Gets and sets a Boolean indicating whether the map will\n * continuously repaint. This information is useful for analyzing performance.\n */\n get repaint(): boolean { return !!this._repaint; }\n set repaint(value: boolean) {\n if (this._repaint !== value) {\n this._repaint = value;\n this.triggerRepaint();\n }\n }\n // show vertices\n get vertices(): boolean { return !!this._vertices; }\n set vertices(value: boolean) { this._vertices = value; this._update(); }\n\n /**\n * Returns the package version of the library\n * @returns Package version of the library\n */\n get version(): string {\n return version;\n }\n\n /**\n * Returns the elevation for the point where the camera is looking.\n * This value corresponds to:\n * \"meters above sea level\" * \"exaggeration\"\n * @returns The elevation.\n */\n getCameraTargetElevation(): number {\n return this.transform.elevation;\n }\n}\n","import type Point from '@mapbox/point-geometry';\n\nimport {DragMoveHandler, DragRotateResult, DragPitchResult, DragHandler} from './drag_handler';\nimport {OneFingerTouchMoveStateManager} from './drag_move_state_manager';\n\nexport interface OneFingerTouchRotateHandler extends DragMoveHandler {}\nexport interface OneFingerTouchPitchHandler extends DragMoveHandler {}\n\nconst assignEvents = (handler: DragHandler) => {\n handler.touchstart = handler.dragStart;\n handler.touchmoveWindow = handler.dragMove;\n handler.touchend = handler.dragEnd;\n};\n\nexport const generateOneFingerTouchRotationHandler = ({enable, clickTolerance, bearingDegreesPerPixelMoved = 0.8}: {\n clickTolerance: number;\n bearingDegreesPerPixelMoved?: number;\n enable?: boolean;\n}): OneFingerTouchRotateHandler => {\n const touchMoveStateManager = new OneFingerTouchMoveStateManager();\n return new DragHandler({\n clickTolerance,\n move: (lastPoint: Point, point: Point) =>\n ({bearingDelta: (point.x - lastPoint.x) * bearingDegreesPerPixelMoved}),\n moveStateManager: touchMoveStateManager,\n enable,\n assignEvents,\n });\n};\n\nexport const generateOneFingerTouchPitchHandler = ({enable, clickTolerance, pitchDegreesPerPixelMoved = -0.5}: {\n clickTolerance: number;\n pitchDegreesPerPixelMoved?: number;\n enable?: boolean;\n}): OneFingerTouchPitchHandler => {\n const touchMoveStateManager = new OneFingerTouchMoveStateManager();\n return new DragHandler({\n clickTolerance,\n move: (lastPoint: Point, point: Point) =>\n ({pitchDelta: (point.y - lastPoint.y) * pitchDegreesPerPixelMoved}),\n moveStateManager: touchMoveStateManager,\n enable,\n assignEvents,\n });\n};\n","import Point from '@mapbox/point-geometry';\n\nimport {DOM} from '../../util/dom';\nimport {extend} from '../../util/util';\nimport {generateMousePitchHandler, generateMouseRotationHandler, MousePitchHandler, MouseRotateHandler} from '../handler/mouse';\nimport {generateOneFingerTouchPitchHandler, generateOneFingerTouchRotationHandler, OneFingerTouchPitchHandler, OneFingerTouchRotateHandler} from '../handler/one_finger_touch_drag';\n\nimport type {Map} from '../map';\nimport type {IControl} from './control';\n\n/**\n * The {@link NavigationControl} options object\n */\ntype NavigationControlOptions = {\n /**\n * If `true` the compass button is included.\n */\n showCompass?: boolean;\n /**\n * If `true` the zoom-in and zoom-out buttons are included.\n */\n showZoom?: boolean;\n /**\n * If `true` the pitch is visualized by rotating X-axis of compass.\n */\n visualizePitch?: boolean;\n};\n\nconst defaultOptions: NavigationControlOptions = {\n showCompass: true,\n showZoom: true,\n visualizePitch: false\n};\n\n/**\n * A `NavigationControl` control contains zoom buttons and a compass.\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * let nav = new NavigationControl();\n * map.addControl(nav, 'top-left');\n * ```\n * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/)\n */\nexport class NavigationControl implements IControl {\n _map: Map;\n options: NavigationControlOptions;\n _container: HTMLElement;\n _zoomInButton: HTMLButtonElement;\n _zoomOutButton: HTMLButtonElement;\n _compass: HTMLButtonElement;\n _compassIcon: HTMLElement;\n _handler: MouseRotateWrapper;\n\n /**\n * @param options - the control's options\n */\n constructor(options?: NavigationControlOptions) {\n this.options = extend({}, defaultOptions, options);\n\n this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');\n this._container.addEventListener('contextmenu', (e) => e.preventDefault());\n\n if (this.options.showZoom) {\n this._zoomInButton = this._createButton('maplibregl-ctrl-zoom-in', (e) => this._map.zoomIn({}, {originalEvent: e}));\n DOM.create('span', 'maplibregl-ctrl-icon', this._zoomInButton).setAttribute('aria-hidden', 'true');\n this._zoomOutButton = this._createButton('maplibregl-ctrl-zoom-out', (e) => this._map.zoomOut({}, {originalEvent: e}));\n DOM.create('span', 'maplibregl-ctrl-icon', this._zoomOutButton).setAttribute('aria-hidden', 'true');\n }\n if (this.options.showCompass) {\n this._compass = this._createButton('maplibregl-ctrl-compass', (e) => {\n if (this.options.visualizePitch) {\n this._map.resetNorthPitch({}, {originalEvent: e});\n } else {\n this._map.resetNorth({}, {originalEvent: e});\n }\n });\n this._compassIcon = DOM.create('span', 'maplibregl-ctrl-icon', this._compass);\n this._compassIcon.setAttribute('aria-hidden', 'true');\n }\n }\n\n _updateZoomButtons = () => {\n const zoom = this._map.getZoom();\n const isMax = zoom === this._map.getMaxZoom();\n const isMin = zoom === this._map.getMinZoom();\n this._zoomInButton.disabled = isMax;\n this._zoomOutButton.disabled = isMin;\n this._zoomInButton.setAttribute('aria-disabled', isMax.toString());\n this._zoomOutButton.setAttribute('aria-disabled', isMin.toString());\n };\n\n _rotateCompassArrow = () => {\n const rotate = this.options.visualizePitch ?\n `scale(${1 / Math.pow(Math.cos(this._map.transform.pitch * (Math.PI / 180)), 0.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${this._map.transform.angle * (180 / Math.PI)}deg)` :\n `rotate(${this._map.transform.angle * (180 / Math.PI)}deg)`;\n\n this._compassIcon.style.transform = rotate;\n };\n\n /** {@inheritDoc IControl.onAdd} */\n onAdd(map: Map) {\n this._map = map;\n if (this.options.showZoom) {\n this._setButtonTitle(this._zoomInButton, 'ZoomIn');\n this._setButtonTitle(this._zoomOutButton, 'ZoomOut');\n this._map.on('zoom', this._updateZoomButtons);\n this._updateZoomButtons();\n }\n if (this.options.showCompass) {\n this._setButtonTitle(this._compass, 'ResetBearing');\n if (this.options.visualizePitch) {\n this._map.on('pitch', this._rotateCompassArrow);\n }\n this._map.on('rotate', this._rotateCompassArrow);\n this._rotateCompassArrow();\n this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch);\n }\n return this._container;\n }\n\n /** {@inheritDoc IControl.onRemove} */\n onRemove() {\n DOM.remove(this._container);\n if (this.options.showZoom) {\n this._map.off('zoom', this._updateZoomButtons);\n }\n if (this.options.showCompass) {\n if (this.options.visualizePitch) {\n this._map.off('pitch', this._rotateCompassArrow);\n }\n this._map.off('rotate', this._rotateCompassArrow);\n this._handler.off();\n delete this._handler;\n }\n\n delete this._map;\n }\n\n _createButton(className: string, fn: (e?: any) => unknown) {\n const a = DOM.create('button', className, this._container) as HTMLButtonElement;\n a.type = 'button';\n a.addEventListener('click', fn);\n return a;\n }\n\n _setButtonTitle = (button: HTMLButtonElement, title: 'ZoomIn' | 'ZoomOut' | 'ResetBearing') => {\n const str = this._map._getUIString(`NavigationControl.${title}`);\n button.title = str;\n button.setAttribute('aria-label', str);\n };\n}\n\nclass MouseRotateWrapper {\n\n map: Map;\n _clickTolerance: number;\n element: HTMLElement;\n // Rotation and pitch handlers are separated due to different _clickTolerance values\n mouseRotate: MouseRotateHandler;\n touchRotate: OneFingerTouchRotateHandler;\n mousePitch: MousePitchHandler;\n touchPitch: OneFingerTouchPitchHandler;\n _startPos: Point;\n _lastPos: Point;\n\n constructor(map: Map, element: HTMLElement, pitch: boolean = false) {\n this._clickTolerance = 10;\n const mapRotateTolerance = map.dragRotate._mouseRotate.getClickTolerance();\n const mapPitchTolerance = map.dragRotate._mousePitch.getClickTolerance();\n this.element = element;\n this.mouseRotate = generateMouseRotationHandler({clickTolerance: mapRotateTolerance, enable: true});\n this.touchRotate = generateOneFingerTouchRotationHandler({clickTolerance: mapRotateTolerance, enable: true});\n this.map = map;\n if (pitch) {\n this.mousePitch = generateMousePitchHandler({clickTolerance: mapPitchTolerance, enable: true});\n this.touchPitch = generateOneFingerTouchPitchHandler({clickTolerance: mapPitchTolerance, enable: true});\n }\n\n DOM.addEventListener(element, 'mousedown', this.mousedown);\n DOM.addEventListener(element, 'touchstart', this.touchstart, {passive: false});\n DOM.addEventListener(element, 'touchcancel', this.reset);\n }\n\n startMouse(e: MouseEvent, point: Point) {\n this.mouseRotate.dragStart(e, point);\n if (this.mousePitch) this.mousePitch.dragStart(e, point);\n DOM.disableDrag();\n }\n\n startTouch(e: TouchEvent, point: Point) {\n this.touchRotate.dragStart(e, point);\n if (this.touchPitch) this.touchPitch.dragStart(e, point);\n DOM.disableDrag();\n }\n\n moveMouse(e: MouseEvent, point: Point) {\n const map = this.map;\n const {bearingDelta} = this.mouseRotate.dragMove(e, point) || {};\n if (bearingDelta) map.setBearing(map.getBearing() + bearingDelta);\n if (this.mousePitch) {\n const {pitchDelta} = this.mousePitch.dragMove(e, point) || {};\n if (pitchDelta) map.setPitch(map.getPitch() + pitchDelta);\n }\n }\n\n moveTouch(e: TouchEvent, point: Point) {\n const map = this.map;\n const {bearingDelta} = this.touchRotate.dragMove(e, point) || {};\n if (bearingDelta) map.setBearing(map.getBearing() + bearingDelta);\n if (this.touchPitch) {\n const {pitchDelta} = this.touchPitch.dragMove(e, point) || {};\n if (pitchDelta) map.setPitch(map.getPitch() + pitchDelta);\n }\n }\n\n off() {\n const element = this.element;\n DOM.removeEventListener(element, 'mousedown', this.mousedown);\n DOM.removeEventListener(element, 'touchstart', this.touchstart, {passive: false});\n DOM.removeEventListener(window, 'touchmove', this.touchmove, {passive: false});\n DOM.removeEventListener(window, 'touchend', this.touchend);\n DOM.removeEventListener(element, 'touchcancel', this.reset);\n this.offTemp();\n }\n\n offTemp() {\n DOM.enableDrag();\n DOM.removeEventListener(window, 'mousemove', this.mousemove);\n DOM.removeEventListener(window, 'mouseup', this.mouseup);\n DOM.removeEventListener(window, 'touchmove', this.touchmove, {passive: false});\n DOM.removeEventListener(window, 'touchend', this.touchend);\n }\n\n mousedown = (e: MouseEvent) => {\n this.startMouse(extend({}, e, {ctrlKey: true, preventDefault: () => e.preventDefault()}), DOM.mousePos(this.element, e));\n DOM.addEventListener(window, 'mousemove', this.mousemove);\n DOM.addEventListener(window, 'mouseup', this.mouseup);\n };\n\n mousemove = (e: MouseEvent) => {\n this.moveMouse(e, DOM.mousePos(this.element, e));\n };\n\n mouseup = (e: MouseEvent) => {\n this.mouseRotate.dragEnd(e);\n if (this.mousePitch) this.mousePitch.dragEnd(e);\n this.offTemp();\n };\n\n touchstart = (e: TouchEvent) => {\n if (e.targetTouches.length !== 1) {\n this.reset();\n } else {\n this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];\n this.startTouch(e, this._startPos);\n DOM.addEventListener(window, 'touchmove', this.touchmove, {passive: false});\n DOM.addEventListener(window, 'touchend', this.touchend);\n }\n };\n\n touchmove = (e: TouchEvent) => {\n if (e.targetTouches.length !== 1) {\n this.reset();\n } else {\n this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];\n this.moveTouch(e, this._lastPos);\n }\n };\n\n touchend = (e: TouchEvent) => {\n if (e.targetTouches.length === 0 &&\n this._startPos &&\n this._lastPos &&\n this._startPos.dist(this._lastPos) < this._clickTolerance) {\n this.element.click();\n }\n delete this._startPos;\n delete this._lastPos;\n this.offTemp();\n };\n\n reset = () => {\n this.mouseRotate.reset();\n if (this.mousePitch) this.mousePitch.reset();\n this.touchRotate.reset();\n if (this.touchPitch) this.touchPitch.reset();\n delete this._startPos;\n delete this._lastPos;\n this.offTemp();\n };\n}\n","let supportsGeolocation;\n\nexport async function checkGeolocationSupport(forceRecalculation = false): Promise {\n if (supportsGeolocation !== undefined && !forceRecalculation) {\n return supportsGeolocation;\n }\n if (window.navigator.permissions === undefined) {\n supportsGeolocation = !!window.navigator.geolocation;\n return supportsGeolocation;\n }\n // navigator.permissions has incomplete browser support\n // https://caniuse.com/#feat=permissions-api\n // Test for the case where a browser disables Geolocation because of an\n // insecure origin\n try {\n const permissions = await window.navigator.permissions.query({name: 'geolocation'});\n supportsGeolocation = permissions.state !== 'denied'; // eslint-disable-line require-atomic-updates\n } catch {\n // Fix for iOS16 which rejects query but still supports geolocation\n supportsGeolocation = !!window.navigator.geolocation; // eslint-disable-line require-atomic-updates\n }\n return supportsGeolocation;\n}\n","import {LngLat} from '../geo/lng_lat';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Transform} from '../geo/transform';\n\n/**\n * Given a LngLat, prior projected position, and a transform, return a new LngLat shifted\n * n × 360° east or west for some n ≥ 0 such that:\n *\n * * the projected location of the result is on screen, if possible, and secondarily:\n * * the difference between the projected location of the result and the prior position\n * is minimized.\n *\n * The object is to preserve perceived object constancy for Popups and Markers as much as\n * possible; they should avoid shifting large distances across the screen, even when the\n * map center changes by ±360° due to automatic wrapping, and when about to go off screen,\n * should wrap just enough to avoid doing so.\n */\nexport function smartWrap(lngLat: LngLat, priorPos: Point, transform: Transform): LngLat {\n const originalLngLat = new LngLat(lngLat.lng, lngLat.lat);\n lngLat = new LngLat(lngLat.lng, lngLat.lat);\n\n // First, try shifting one world in either direction, and see if either is closer to the\n // prior position. This preserves object constancy when the map center is auto-wrapped\n // during animations.\n if (priorPos) {\n const left = new LngLat(lngLat.lng - 360, lngLat.lat);\n const right = new LngLat(lngLat.lng + 360, lngLat.lat);\n const delta = transform.locationPoint(lngLat).distSqr(priorPos);\n if (transform.locationPoint(left).distSqr(priorPos) < delta) {\n lngLat = left;\n } else if (transform.locationPoint(right).distSqr(priorPos) < delta) {\n lngLat = right;\n }\n }\n\n // Second, wrap toward the center until the new position is on screen, or we can't get\n // any closer.\n while (Math.abs(lngLat.lng - transform.center.lng) > 180) {\n const pos = transform.locationPoint(lngLat);\n if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) {\n break;\n }\n if (lngLat.lng > transform.center.lng) {\n lngLat.lng -= 360;\n } else {\n lngLat.lng += 360;\n }\n }\n\n // Apply the change only if new coord is below horizon\n if (lngLat.lng !== originalLngLat.lng &&\n transform.locationPoint(lngLat).y > (transform.height / 2 - transform.getHorizon())) {\n return lngLat;\n }\n\n return originalLngLat;\n}\n","/**\n * Where to position the anchor.\n * Used by a popup and a marker.\n */\nexport type PositionAnchor = 'center' | 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\nexport const anchorTranslate: {\n [_ in PositionAnchor]: string;\n} = {\n 'center': 'translate(-50%,-50%)',\n 'top': 'translate(-50%,0)',\n 'top-left': 'translate(0,0)',\n 'top-right': 'translate(-100%,0)',\n 'bottom': 'translate(-50%,-100%)',\n 'bottom-left': 'translate(0,-100%)',\n 'bottom-right': 'translate(-100%,-100%)',\n 'left': 'translate(0,-50%)',\n 'right': 'translate(-100%,-50%)'\n};\n\nexport function applyAnchorClass(element: HTMLElement, anchor: PositionAnchor, prefix: string) {\n const classList = element.classList;\n for (const key in anchorTranslate) {\n classList.remove(`maplibregl-${prefix}-anchor-${key}`);\n }\n classList.add(`maplibregl-${prefix}-anchor-${anchor}`);\n}\n","import {DOM} from '../util/dom';\nimport {browser} from '../util/browser';\nimport {LngLat} from '../geo/lng_lat';\nimport Point from '@mapbox/point-geometry';\nimport {smartWrap} from '../util/smart_wrap';\nimport {anchorTranslate, applyAnchorClass} from './anchor';\nimport type {PositionAnchor} from './anchor';\nimport {Event, Evented} from '../util/evented';\nimport type {Map} from './map';\nimport {Popup, Offset} from './popup';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport type {MapMouseEvent, MapTouchEvent} from './events';\nimport type {PointLike} from './camera';\n\n/**\n * Alignment options of rotation and pitch\n */\ntype Alignment = 'map' | 'viewport' | 'auto';\n\n/**\n * The {@link Marker} options object\n */\ntype MarkerOptions = {\n /**\n * DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.\n */\n element?: HTMLElement;\n /**\n * Space-separated CSS class names to add to marker element.\n */\n className?: string;\n /**\n * The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up.\n */\n offset?: PointLike;\n /**\n * A string indicating the part of the Marker that should be positioned closest to the coordinate set via {@link Marker#setLngLat}.\n * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`.\n * @defaultValue 'center'\n * */\n anchor?: PositionAnchor;\n /**\n * The color to use for the default marker if options.element is not provided. The default is light blue.\n * @defaultValue '#3FB1CE'\n */\n color?: string;\n /**\n * The scale to use for the default marker if options.element is not provided. The default scale corresponds to a height of `41px` and a width of `27px`.\n * @defaultValue 1\n */\n scale?: number;\n /**\n * A boolean indicating whether or not a marker is able to be dragged to a new position on the map.\n * @defaultValue false\n */\n draggable?: boolean;\n /**\n * The max number of pixels a user can shift the mouse pointer during a click on the marker for it to be considered a valid click (as opposed to a marker drag). The default is to inherit map's clickTolerance.\n * @defaultValue 0\n */\n clickTolerance?: number;\n /**\n * The rotation angle of the marker in degrees, relative to its respective `rotationAlignment` setting. A positive value will rotate the marker clockwise.\n * @defaultValue 0\n */\n rotation?: number;\n /**\n * `map` aligns the `Marker`'s rotation relative to the map, maintaining a bearing as the map rotates. `viewport` aligns the `Marker`'s rotation relative to the viewport, agnostic to map rotations. `auto` is equivalent to `viewport`.\n * @defaultValue 'auto'\n */\n rotationAlignment?: Alignment;\n /**\n * `map` aligns the `Marker` to the plane of the map. `viewport` aligns the `Marker` to the plane of the viewport. `auto` automatically matches the value of `rotationAlignment`.\n * @defaultValue 'auto'\n */\n pitchAlignment?: Alignment;\n /**\n * Marker's opacity when it's in clear view (not behind 3d terrain)\n * @defaultValue 1\n */\n opacity?: string;\n /**\n * Marker's opacity when it's behind 3d terrain\n * @defaultValue 0.2\n */\n opacityWhenCovered?: string;\n /**\n * If `true`, rounding is disabled for placement of the marker, allowing for\n * subpixel positioning and smoother movement when the marker is translated.\n * @defaultValue false\n */\n subpixelPositioning?: boolean;\n};\n\n/**\n * Creates a marker component\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * let marker = new Marker()\n * .setLngLat([30.5, 50.5])\n * .addTo(map);\n * ```\n *\n * @example\n * Set options\n * ```ts\n * let marker = new Marker({\n * color: \"#FFFFFF\",\n * draggable: true\n * }).setLngLat([30.5, 50.5])\n * .addTo(map);\n * ```\n * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/)\n * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/)\n *\n * ## Events\n *\n * **Event** `dragstart` of type {@link Event} will be fired when dragging starts.\n *\n * **Event** `drag` of type {@link Event} will be fired while dragging.\n *\n * **Event** `dragend` of type {@link Event} will be fired when the marker is finished being dragged.\n */\nexport class Marker extends Evented {\n _map: Map;\n _anchor: PositionAnchor;\n _offset: Point;\n _element: HTMLElement;\n _popup: Popup;\n _lngLat: LngLat;\n _pos: Point;\n _flatPos: Point;\n _color: string;\n _scale: number;\n _defaultMarker: boolean;\n _draggable: boolean;\n _clickTolerance: number;\n _isDragging: boolean;\n _state: 'inactive' | 'pending' | 'active'; // used for handling drag events\n _positionDelta: Point;\n _pointerdownPos: Point;\n _rotation: number;\n _pitchAlignment: Alignment;\n _rotationAlignment: Alignment;\n _originalTabIndex: string; // original tabindex of _element\n _opacity: string;\n _opacityWhenCovered: string;\n _opacityTimeout: ReturnType;\n _subpixelPositioning: boolean;\n\n /**\n * @param options - the options\n */\n constructor(options?: MarkerOptions) {\n super();\n\n this._anchor = options && options.anchor || 'center';\n this._color = options && options.color || '#3FB1CE';\n this._scale = options && options.scale || 1;\n this._draggable = options && options.draggable || false;\n this._clickTolerance = options && options.clickTolerance || 0;\n this._subpixelPositioning = options && options.subpixelPositioning || false;\n this._isDragging = false;\n this._state = 'inactive';\n this._rotation = options && options.rotation || 0;\n this._rotationAlignment = options && options.rotationAlignment || 'auto';\n this._pitchAlignment = options && options.pitchAlignment && options.pitchAlignment !== 'auto' ? options.pitchAlignment : this._rotationAlignment;\n this.setOpacity(); // set default opacity\n this.setOpacity(options?.opacity, options?.opacityWhenCovered);\n\n if (!options || !options.element) {\n this._defaultMarker = true;\n this._element = DOM.create('div');\n\n // create default map marker SVG\n const svg = DOM.createNS('http://www.w3.org/2000/svg', 'svg');\n const defaultHeight = 41;\n const defaultWidth = 27;\n svg.setAttributeNS(null, 'display', 'block');\n svg.setAttributeNS(null, 'height', `${defaultHeight}px`);\n svg.setAttributeNS(null, 'width', `${defaultWidth}px`);\n svg.setAttributeNS(null, 'viewBox', `0 0 ${defaultWidth} ${defaultHeight}`);\n\n const markerLarge = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n markerLarge.setAttributeNS(null, 'stroke', 'none');\n markerLarge.setAttributeNS(null, 'stroke-width', '1');\n markerLarge.setAttributeNS(null, 'fill', 'none');\n markerLarge.setAttributeNS(null, 'fill-rule', 'evenodd');\n\n const page1 = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n page1.setAttributeNS(null, 'fill-rule', 'nonzero');\n\n const shadow = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n shadow.setAttributeNS(null, 'transform', 'translate(3.0, 29.0)');\n shadow.setAttributeNS(null, 'fill', '#000000');\n\n const ellipses = [\n {'rx': '10.5', 'ry': '5.25002273'},\n {'rx': '10.5', 'ry': '5.25002273'},\n {'rx': '9.5', 'ry': '4.77275007'},\n {'rx': '8.5', 'ry': '4.29549936'},\n {'rx': '7.5', 'ry': '3.81822308'},\n {'rx': '6.5', 'ry': '3.34094679'},\n {'rx': '5.5', 'ry': '2.86367051'},\n {'rx': '4.5', 'ry': '2.38636864'}\n ];\n\n for (const data of ellipses) {\n const ellipse = DOM.createNS('http://www.w3.org/2000/svg', 'ellipse');\n ellipse.setAttributeNS(null, 'opacity', '0.04');\n ellipse.setAttributeNS(null, 'cx', '10.5');\n ellipse.setAttributeNS(null, 'cy', '5.80029008');\n ellipse.setAttributeNS(null, 'rx', data['rx']);\n ellipse.setAttributeNS(null, 'ry', data['ry']);\n shadow.appendChild(ellipse);\n }\n\n const background = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n background.setAttributeNS(null, 'fill', this._color);\n\n const bgPath = DOM.createNS('http://www.w3.org/2000/svg', 'path');\n bgPath.setAttributeNS(null, 'd', 'M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z');\n\n background.appendChild(bgPath);\n\n const border = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n border.setAttributeNS(null, 'opacity', '0.25');\n border.setAttributeNS(null, 'fill', '#000000');\n\n const borderPath = DOM.createNS('http://www.w3.org/2000/svg', 'path');\n borderPath.setAttributeNS(null, 'd', 'M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z');\n\n border.appendChild(borderPath);\n\n const maki = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n maki.setAttributeNS(null, 'transform', 'translate(6.0, 7.0)');\n maki.setAttributeNS(null, 'fill', '#FFFFFF');\n\n const circleContainer = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n circleContainer.setAttributeNS(null, 'transform', 'translate(8.0, 8.0)');\n\n const circle1 = DOM.createNS('http://www.w3.org/2000/svg', 'circle');\n circle1.setAttributeNS(null, 'fill', '#000000');\n circle1.setAttributeNS(null, 'opacity', '0.25');\n circle1.setAttributeNS(null, 'cx', '5.5');\n circle1.setAttributeNS(null, 'cy', '5.5');\n circle1.setAttributeNS(null, 'r', '5.4999962');\n\n const circle2 = DOM.createNS('http://www.w3.org/2000/svg', 'circle');\n circle2.setAttributeNS(null, 'fill', '#FFFFFF');\n circle2.setAttributeNS(null, 'cx', '5.5');\n circle2.setAttributeNS(null, 'cy', '5.5');\n circle2.setAttributeNS(null, 'r', '5.4999962');\n\n circleContainer.appendChild(circle1);\n circleContainer.appendChild(circle2);\n\n page1.appendChild(shadow);\n page1.appendChild(background);\n page1.appendChild(border);\n page1.appendChild(maki);\n page1.appendChild(circleContainer);\n\n svg.appendChild(page1);\n\n svg.setAttributeNS(null, 'height', `${defaultHeight * this._scale}px`);\n svg.setAttributeNS(null, 'width', `${defaultWidth * this._scale}px`);\n\n this._element.appendChild(svg);\n\n // if no element and no offset option given apply an offset for the default marker\n // the -14 as the y value of the default marker offset was determined as follows\n //\n // the marker tip is at the center of the shadow ellipse from the default svg\n // the y value of the center of the shadow ellipse relative to the svg top left is \"shadow transform translate-y (29.0) + ellipse cy (5.80029008)\"\n // offset to the svg center \"height (41 / 2)\" gives (29.0 + 5.80029008) - (41 / 2) and rounded for an integer pixel offset gives 14\n // negative is used to move the marker up from the center so the tip is at the Marker lngLat\n this._offset = Point.convert(options && options.offset || [0, -14]);\n } else {\n this._element = options.element;\n this._offset = Point.convert(options && options.offset || [0, 0]);\n }\n\n this._element.classList.add('maplibregl-marker');\n this._element.addEventListener('dragstart', (e: DragEvent) => {\n e.preventDefault();\n });\n this._element.addEventListener('mousedown', (e: MouseEvent) => {\n // prevent focusing on click\n e.preventDefault();\n });\n applyAnchorClass(this._element, this._anchor, 'marker');\n\n if (options && options.className) {\n for (const name of options.className.split(' ')) {\n this._element.classList.add(name);\n }\n }\n\n this._popup = null;\n }\n\n /**\n * Attaches the `Marker` to a `Map` object.\n * @param map - The MapLibre GL JS map to add the marker to.\n * @example\n * ```ts\n * let marker = new Marker()\n * .setLngLat([30.5, 50.5])\n * .addTo(map); // add the marker to the map\n * ```\n */\n addTo(map: Map): this {\n this.remove();\n this._map = map;\n this._element.setAttribute('aria-label', map._getUIString('Marker.Title'));\n\n map.getCanvasContainer().appendChild(this._element);\n map.on('move', this._update);\n map.on('moveend', this._update);\n map.on('terrain', this._update);\n\n this.setDraggable(this._draggable);\n this._update();\n\n // If we attached the `click` listener to the marker element, the popup\n // would close once the event propagated to `map` due to the\n // `Popup#_onClickClose` listener.\n this._map.on('click', this._onMapClick);\n\n return this;\n }\n\n /**\n * Removes the marker from a map\n * @example\n * ```ts\n * let marker = new Marker().addTo(map);\n * marker.remove();\n * ```\n */\n remove(): this {\n if (this._opacityTimeout) {\n clearTimeout(this._opacityTimeout);\n delete this._opacityTimeout;\n }\n if (this._map) {\n this._map.off('click', this._onMapClick);\n this._map.off('move', this._update);\n this._map.off('moveend', this._update);\n this._map.off('terrain', this._update);\n this._map.off('mousedown', this._addDragHandler);\n this._map.off('touchstart', this._addDragHandler);\n this._map.off('mouseup', this._onUp);\n this._map.off('touchend', this._onUp);\n this._map.off('mousemove', this._onMove);\n this._map.off('touchmove', this._onMove);\n delete this._map;\n }\n DOM.remove(this._element);\n if (this._popup) this._popup.remove();\n return this;\n }\n\n /**\n * Get the marker's geographical location.\n *\n * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously\n * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep\n * the marker on screen.\n *\n * @returns A {@link LngLat} describing the marker's location.\n * @example\n * ```ts\n * // Store the marker's longitude and latitude coordinates in a variable\n * let lngLat = marker.getLngLat();\n * // Print the marker's longitude and latitude values in the console\n * console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat )\n * ```\n * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/)\n */\n getLngLat(): LngLat {\n return this._lngLat;\n }\n\n /**\n * Set the marker's geographical position and move it.\n * @param lnglat - A {@link LngLat} describing where the marker should be located.\n * @example\n * Create a new marker, set the longitude and latitude, and add it to the map\n * ```ts\n * new Marker()\n * .setLngLat([-65.017, -16.457])\n * .addTo(map);\n * ```\n * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/)\n * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/)\n */\n setLngLat(lnglat: LngLatLike): this {\n this._lngLat = LngLat.convert(lnglat);\n this._pos = null;\n if (this._popup) this._popup.setLngLat(this._lngLat);\n this._update();\n return this;\n }\n\n /**\n * Returns the `Marker`'s HTML element.\n * @returns element\n */\n getElement(): HTMLElement {\n return this._element;\n }\n\n /**\n * Binds a {@link Popup} to the {@link Marker}.\n * @param popup - An instance of the {@link Popup} class. If undefined or null, any popup\n * set on this {@link Marker} instance is unset.\n * @example\n * ```ts\n * let marker = new Marker()\n * .setLngLat([0, 0])\n * .setPopup(new Popup().setHTML(\"

Hello World!

\")) // add popup\n * .addTo(map);\n * ```\n * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/)\n */\n setPopup(popup?: Popup | null): this {\n if (this._popup) {\n this._popup.remove();\n this._popup = null;\n this._element.removeEventListener('keypress', this._onKeyPress);\n\n if (!this._originalTabIndex) {\n this._element.removeAttribute('tabindex');\n }\n }\n\n if (popup) {\n if (!('offset' in popup.options)) {\n const markerHeight = 41 - (5.8 / 2);\n const markerRadius = 13.5;\n const linearOffset = Math.abs(markerRadius) / Math.SQRT2;\n popup.options.offset = this._defaultMarker ? {\n 'top': [0, 0],\n 'top-left': [0, 0],\n 'top-right': [0, 0],\n 'bottom': [0, -markerHeight],\n 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n 'left': [markerRadius, (markerHeight - markerRadius) * -1],\n 'right': [-markerRadius, (markerHeight - markerRadius) * -1]\n } as Offset : this._offset;\n }\n this._popup = popup;\n\n this._originalTabIndex = this._element.getAttribute('tabindex');\n if (!this._originalTabIndex) {\n this._element.setAttribute('tabindex', '0');\n }\n this._element.addEventListener('keypress', this._onKeyPress);\n }\n\n return this;\n }\n\n /**\n * Set the option to allow subpixel positioning of the marker by passing a boolean\n *\n * @param value - when set to `true`, subpixel positioning is enabled for the marker.\n *\n * @example\n * ```ts\n * let marker = new Marker()\n * marker.setSubpixelPositioning(true);\n * ```\n */\n setSubpixelPositioning(value: boolean) {\n this._subpixelPositioning = value;\n return this;\n }\n\n _onKeyPress = (e: KeyboardEvent) => {\n const code = e.code;\n const legacyCode = e.charCode || e.keyCode;\n\n if (\n (code === 'Space') || (code === 'Enter') ||\n (legacyCode === 32) || (legacyCode === 13) // space or enter\n ) {\n this.togglePopup();\n }\n };\n\n _onMapClick = (e: MapMouseEvent) => {\n const targetElement = e.originalEvent.target;\n const element = this._element;\n\n if (this._popup && (targetElement === element || element.contains(targetElement as any))) {\n this.togglePopup();\n }\n };\n\n /**\n * Returns the {@link Popup} instance that is bound to the {@link Marker}.\n * @returns popup\n * @example\n * ```ts\n * let marker = new Marker()\n * .setLngLat([0, 0])\n * .setPopup(new Popup().setHTML(\"

Hello World!

\"))\n * .addTo(map);\n *\n * console.log(marker.getPopup()); // return the popup instance\n * ```\n */\n getPopup(): Popup {\n return this._popup;\n }\n\n /**\n * Opens or closes the {@link Popup} instance that is bound to the {@link Marker}, depending on the current state of the {@link Popup}.\n * @example\n * ```ts\n * let marker = new Marker()\n * .setLngLat([0, 0])\n * .setPopup(new Popup().setHTML(\"

Hello World!

\"))\n * .addTo(map);\n *\n * marker.togglePopup(); // toggle popup open or closed\n * ```\n */\n togglePopup(): this {\n const popup = this._popup;\n\n if (this._element.style.opacity === this._opacityWhenCovered) return this;\n\n if (!popup) return this;\n else if (popup.isOpen()) popup.remove();\n else {\n popup.setLngLat(this._lngLat);\n popup.addTo(this._map);\n }\n return this;\n }\n\n _updateOpacity(force: boolean = false) {\n const terrain = this._map?.terrain;\n if (!terrain) {\n if (this._element.style.opacity !== this._opacity) { this._element.style.opacity = this._opacity; }\n return;\n }\n if (force) {\n this._opacityTimeout = null;\n } else {\n if (this._opacityTimeout) { return; }\n this._opacityTimeout = setTimeout(() => {\n this._opacityTimeout = null;\n }, 100);\n }\n\n const map = this._map;\n\n // Read depth framebuffer, getting position of terrain in line of sight to marker\n const terrainDistance = map.terrain.depthAtPoint(this._pos);\n // Transform marker position to clip space\n const elevation = map.terrain.getElevationForLngLatZoom(this._lngLat, map.transform.tileZoom);\n const markerDistance = map.transform.lngLatToCameraDepth(this._lngLat, elevation);\n\n const forgiveness = .006;\n if (markerDistance - terrainDistance < forgiveness) {\n this._element.style.opacity = this._opacity;\n return;\n }\n // If the base is obscured, use the offset to check if the marker's center is obscured.\n const metersToCenter = -this._offset.y / map.transform._pixelPerMeter;\n const elevationToCenter = Math.sin(map.getPitch() * Math.PI / 180) * metersToCenter;\n const terrainDistanceCenter = map.terrain.depthAtPoint(new Point(this._pos.x, this._pos.y - this._offset.y));\n const markerDistanceCenter = map.transform.lngLatToCameraDepth(this._lngLat, elevation + elevationToCenter);\n // Display at full opacity if center is visible.\n const centerIsInvisible = markerDistanceCenter - terrainDistanceCenter > forgiveness;\n\n if (this._popup?.isOpen() && centerIsInvisible) this._popup.remove();\n this._element.style.opacity = centerIsInvisible ? this._opacityWhenCovered : this._opacity;\n }\n\n _update = (e?: { type: 'move' | 'moveend' | 'terrain' | 'render' }) => {\n if (!this._map) return;\n\n const isFullyLoaded = this._map.loaded() && !this._map.isMoving();\n if (e?.type === 'terrain' || (e?.type === 'render' && !isFullyLoaded)) {\n this._map.once('render', this._update);\n }\n\n if (this._map.transform.renderWorldCopies) {\n this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform);\n } else {\n this._lngLat = this._lngLat?.wrap();\n }\n\n this._flatPos = this._pos = this._map.project(this._lngLat)._add(this._offset);\n if (this._map.terrain) {\n // flat position is saved because smartWrap needs non-elevated points\n this._flatPos = this._map.transform.locationPoint(this._lngLat)._add(this._offset);\n }\n\n let rotation = '';\n if (this._rotationAlignment === 'viewport' || this._rotationAlignment === 'auto') {\n rotation = `rotateZ(${this._rotation}deg)`;\n } else if (this._rotationAlignment === 'map') {\n rotation = `rotateZ(${this._rotation - this._map.getBearing()}deg)`;\n }\n\n let pitch = '';\n if (this._pitchAlignment === 'viewport' || this._pitchAlignment === 'auto') {\n pitch = 'rotateX(0deg)';\n } else if (this._pitchAlignment === 'map') {\n pitch = `rotateX(${this._map.getPitch()}deg)`;\n }\n\n // because rounding the coordinates at every `move` event causes stuttered zooming\n // we only round them when _update is called with `moveend` or when its called with\n // no arguments (when the Marker is initialized or Marker#setLngLat is invoked).\n if (!this._subpixelPositioning && (!e || e.type === 'moveend')) {\n this._pos = this._pos.round();\n }\n\n DOM.setTransform(this._element, `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`);\n\n browser.frameAsync(new AbortController()).then(() => { // Run _updateOpacity only after painter.render and drawDepth\n this._updateOpacity(e && e.type === 'moveend');\n }).catch(() => {});\n };\n\n /**\n * Get the marker's offset.\n * @returns The marker's screen coordinates in pixels.\n */\n getOffset(): Point {\n return this._offset;\n }\n\n /**\n * Sets the offset of the marker\n * @param offset - The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up.\n */\n setOffset(offset: PointLike): this {\n this._offset = Point.convert(offset);\n this._update();\n return this;\n }\n\n /**\n * Adds a CSS class to the marker element.\n *\n * @param className - on-empty string with CSS class name to add to marker element\n *\n * @example\n * ```\n * let marker = new Marker()\n * marker.addClassName('some-class')\n * ```\n */\n addClassName(className: string) {\n this._element.classList.add(className);\n }\n\n /**\n * Removes a CSS class from the marker element.\n *\n * @param className - Non-empty string with CSS class name to remove from marker element\n *\n * @example\n * ```ts\n * let marker = new Marker()\n * marker.removeClassName('some-class')\n * ```\n */\n removeClassName(className: string) {\n this._element.classList.remove(className);\n }\n\n /**\n * Add or remove the given CSS class on the marker element, depending on whether the element currently has that class.\n *\n * @param className - Non-empty string with CSS class name to add/remove\n *\n * @returns if the class was removed return false, if class was added, then return true\n *\n * @example\n * ```ts\n * let marker = new Marker()\n * marker.toggleClassName('toggleClass')\n * ```\n */\n toggleClassName(className: string): boolean {\n return this._element.classList.toggle(className);\n }\n\n _onMove = (e: MapMouseEvent | MapTouchEvent) => {\n if (!this._isDragging) {\n const clickTolerance = this._clickTolerance || this._map._clickTolerance;\n this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance;\n }\n if (!this._isDragging) return;\n\n this._pos = e.point.sub(this._positionDelta);\n this._lngLat = this._map.unproject(this._pos);\n this.setLngLat(this._lngLat);\n // suppress click event so that popups don't toggle on drag\n this._element.style.pointerEvents = 'none';\n\n // make sure dragstart only fires on the first move event after mousedown.\n // this can't be on mousedown because that event doesn't necessarily\n // imply that a drag is about to happen.\n if (this._state === 'pending') {\n this._state = 'active';\n this.fire(new Event('dragstart'));\n }\n this.fire(new Event('drag'));\n };\n\n _onUp = () => {\n // revert to normal pointer event handling\n this._element.style.pointerEvents = 'auto';\n this._positionDelta = null;\n this._pointerdownPos = null;\n this._isDragging = false;\n this._map.off('mousemove', this._onMove);\n this._map.off('touchmove', this._onMove);\n\n // only fire dragend if it was preceded by at least one drag event\n if (this._state === 'active') {\n this.fire(new Event('dragend'));\n }\n\n this._state = 'inactive';\n };\n\n _addDragHandler = (e: MapMouseEvent | MapTouchEvent) => {\n if (this._element.contains(e.originalEvent.target as any)) {\n e.preventDefault();\n\n // We need to calculate the pixel distance between the click point\n // and the marker position, with the offset accounted for. Then we\n // can subtract this distance from the mousemove event's position\n // to calculate the new marker position.\n // If we don't do this, the marker 'jumps' to the click position\n // creating a jarring UX effect.\n this._positionDelta = e.point.sub(this._pos).add(this._offset);\n\n this._pointerdownPos = e.point;\n\n this._state = 'pending';\n this._map.on('mousemove', this._onMove);\n this._map.on('touchmove', this._onMove);\n this._map.once('mouseup', this._onUp);\n this._map.once('touchend', this._onUp);\n }\n };\n\n /**\n * Sets the `draggable` property and functionality of the marker\n * @param shouldBeDraggable - Turns drag functionality on/off\n */\n setDraggable(shouldBeDraggable?: boolean): this {\n this._draggable = !!shouldBeDraggable; // convert possible undefined value to false\n\n // handle case where map may not exist yet\n // e.g. when setDraggable is called before addTo\n if (this._map) {\n if (shouldBeDraggable) {\n this._map.on('mousedown', this._addDragHandler);\n this._map.on('touchstart', this._addDragHandler);\n } else {\n this._map.off('mousedown', this._addDragHandler);\n this._map.off('touchstart', this._addDragHandler);\n }\n }\n\n return this;\n }\n\n /**\n * Returns true if the marker can be dragged\n * @returns True if the marker is draggable.\n */\n isDraggable(): boolean {\n return this._draggable;\n }\n\n /**\n * Sets the `rotation` property of the marker.\n * @param rotation - The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker#setRotationAlignment} setting.\n */\n setRotation(rotation?: number): this {\n this._rotation = rotation || 0;\n this._update();\n return this;\n }\n\n /**\n * Returns the current rotation angle of the marker (in degrees).\n * @returns The current rotation angle of the marker.\n */\n getRotation(): number {\n return this._rotation;\n }\n\n /**\n * Sets the `rotationAlignment` property of the marker.\n * @param alignment - Sets the `rotationAlignment` property of the marker. defaults to 'auto'\n */\n setRotationAlignment(alignment?: Alignment): this {\n this._rotationAlignment = alignment || 'auto';\n this._update();\n return this;\n }\n\n /**\n * Returns the current `rotationAlignment` property of the marker.\n * @returns The current rotational alignment of the marker.\n */\n getRotationAlignment(): Alignment {\n return this._rotationAlignment;\n }\n\n /**\n * Sets the `pitchAlignment` property of the marker.\n * @param alignment - Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`.\n */\n setPitchAlignment(alignment?: Alignment): this {\n this._pitchAlignment = alignment && alignment !== 'auto' ? alignment : this._rotationAlignment;\n this._update();\n return this;\n }\n\n /**\n * Returns the current `pitchAlignment` property of the marker.\n * @returns The current pitch alignment of the marker in degrees.\n */\n getPitchAlignment(): Alignment {\n return this._pitchAlignment;\n }\n\n /**\n * Sets the `opacity` and `opacityWhenCovered` properties of the marker.\n * When called without arguments, resets opacity and opacityWhenCovered to defaults\n * @param opacity - Sets the `opacity` property of the marker.\n * @param opacityWhenCovered - Sets the `opacityWhenCovered` property of the marker.\n */\n setOpacity(opacity?: string, opacityWhenCovered?: string): this {\n if (opacity === undefined && opacityWhenCovered === undefined) {\n this._opacity = '1';\n this._opacityWhenCovered = '0.2';\n }\n if (opacity !== undefined) {\n this._opacity = opacity;\n }\n if (opacityWhenCovered !== undefined) {\n this._opacityWhenCovered = opacityWhenCovered;\n }\n if (this._map) {\n this._updateOpacity(true);\n }\n return this;\n }\n}\n","import {Event, Evented} from '../../util/evented';\nimport {DOM} from '../../util/dom';\nimport {extend, warnOnce} from '../../util/util';\nimport {checkGeolocationSupport} from '../../util/geolocation_support';\nimport {LngLat} from '../../geo/lng_lat';\nimport {Marker} from '../marker';\n\nimport type {Map} from '../map';\nimport type {FitBoundsOptions} from '../camera';\nimport type {IControl} from './control';\nimport {LngLatBounds} from '../../geo/lng_lat_bounds';\n\n/**\n * The {@link GeolocateControl} options object\n */\ntype GeolocateControlOptions = {\n /**\n * A Geolocation API [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object.\n * @defaultValue `{enableHighAccuracy: false, timeout: 6000}`\n */\n positionOptions?: PositionOptions;\n /**\n * A options object to use when the map is panned and zoomed to the user's location. The default is to use a `maxZoom` of 15 to limit how far the map will zoom in for very accurate locations.\n */\n fitBoundsOptions?: FitBoundsOptions;\n /**\n * If `true` the `GeolocateControl` becomes a toggle button and when active the map will receive updates to the user's location as it changes.\n * @defaultValue false\n */\n trackUserLocation?: boolean;\n /**\n * By default, if `showUserLocation` is `true`, a transparent circle will be drawn around the user location indicating the accuracy (95% confidence level) of the user's location. Set to `false` to disable. Always disabled when `showUserLocation` is `false`.\n * @defaultValue true\n */\n showAccuracyCircle?: boolean;\n /**\n * By default a dot will be shown on the map at the user's location. Set to `false` to disable.\n * @defaultValue true\n */\n showUserLocation?: boolean;\n};\n\nconst defaultOptions: GeolocateControlOptions = {\n positionOptions: {\n enableHighAccuracy: false,\n maximumAge: 0,\n timeout: 6000 /* 6 sec */\n },\n fitBoundsOptions: {\n maxZoom: 15\n },\n trackUserLocation: false,\n showAccuracyCircle: true,\n showUserLocation: true\n};\n\nlet numberOfWatches = 0;\nlet noTimeout = false;\n\n/**\n * A `GeolocateControl` control provides a button that uses the browser's geolocation\n * API to locate the user on the map.\n *\n * Not all browsers support geolocation,\n * and some users may disable the feature. Geolocation support for modern\n * browsers including Chrome requires sites to be served over HTTPS. If\n * geolocation support is not available, the `GeolocateControl` will show\n * as disabled.\n *\n * The zoom level applied will depend on the accuracy of the geolocation provided by the device.\n *\n * The `GeolocateControl` has two modes. If `trackUserLocation` is `false` (default) the control acts as a button, which when pressed will set the map's camera to target the user location. If the user moves, the map won't update. This is most suited for the desktop. If `trackUserLocation` is `true` the control acts as a toggle button that when active the user's location is actively monitored for changes. In this mode the `GeolocateControl` has three interaction states:\n * * active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center. Initial state and upon clicking the `GeolocateControl` button.\n * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement.\n * * disabled - occurs if Geolocation is not available, disabled or denied.\n *\n * These interaction states can't be controlled programmatically, rather they are set based on user interactions.\n *\n * ## State Diagram\n * ![GeolocateControl state diagram](https://github.com/maplibre/maplibre-gl-js/assets/3269297/78e720e5-d781-4da8-9803-a7a0e6aaaa9f)\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * map.addControl(new GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * }));\n * ```\n * @see [Locate the user](https://maplibre.org/maplibre-gl-js/docs/examples/locate-user/)\n *\n * ## Events\n *\n * **Event** `trackuserlocationend` of type {@link Event} will be fired when the `GeolocateControl` changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when `trackUserLocation` is `true`. In the background state, the dot on the map will update with location updates but the camera will not.\n *\n * **Event** `trackuserlocationstart` of type {@link Event} will be fired when the `GeolocateControl` changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a `geolocate` event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no `geolocate` event will follow unless the users's location changes).\n *\n * **Event** `userlocationlostfocus` of type {@link Event} will be fired when the `GeolocateControl` changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when `trackUserLocation` is `true`. In the background state, the dot on the map will update with location updates but the camera will not.\n *\n * **Event** `userlocationfocus` of type {@link Event} will be fired when the `GeolocateControl` changes to the active lock state, which happens upon the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state.\n *\n * **Event** `geolocate` of type {@link Event} will be fired on each Geolocation API position update which returned as success.\n * `data` - The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition).\n *\n * **Event** `error` of type {@link Event} will be fired on each Geolocation API position update which returned as an error.\n * `data` - The returned [PositionError](https://developer.mozilla.org/en-US/docs/Web/API/PositionError) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition).\n *\n * **Event** `outofmaxbounds` of type {@link Event} will be fired on each Geolocation API position update which returned as success but user position is out of map `maxBounds`.\n * `data` - The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition).\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when a trackuserlocationend event occurs.\n * geolocate.on('trackuserlocationend', () => {\n * console.log('A trackuserlocationend event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when a trackuserlocationstart event occurs.\n * geolocate.on('trackuserlocationstart', () => {\n * console.log('A trackuserlocationstart event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an userlocationlostfocus event occurs.\n * geolocate.on('userlocationlostfocus', function() {\n * console.log('An userlocationlostfocus event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an userlocationfocus event occurs.\n * geolocate.on('userlocationfocus', function() {\n * console.log('An userlocationfocus event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when a geolocate event occurs.\n * geolocate.on('geolocate', () => {\n * console.log('A geolocate event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an error event occurs.\n * geolocate.on('error', () => {\n * console.log('An error event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an outofmaxbounds event occurs.\n * geolocate.on('outofmaxbounds', () => {\n * console.log('An outofmaxbounds event has occurred.')\n * });\n * ```\n */\nexport class GeolocateControl extends Evented implements IControl {\n _map: Map;\n options: GeolocateControlOptions;\n _container: HTMLElement;\n _dotElement: HTMLElement;\n _circleElement: HTMLElement;\n _geolocateButton: HTMLButtonElement;\n _geolocationWatchID: number;\n _timeoutId: ReturnType;\n /* Geolocate Control Watch States\n * This is the private state of the control.\n *\n * OFF\n * off/inactive\n * WAITING_ACTIVE\n * Geolocate Control was clicked but still waiting for Geolocation API response with user location\n * ACTIVE_LOCK\n * Showing the user location as a dot AND tracking the camera to be fixed to their location. If their location changes the map moves to follow.\n * ACTIVE_ERROR\n * There was en error from the Geolocation API while trying to show and track the user location.\n * BACKGROUND\n * Showing the user location as a dot but the camera doesn't follow their location as it changes.\n * BACKGROUND_ERROR\n * There was an error from the Geolocation API while trying to show (but not track) the user location.\n */\n _watchState: 'OFF' | 'ACTIVE_LOCK' | 'WAITING_ACTIVE' | 'ACTIVE_ERROR' | 'BACKGROUND' | 'BACKGROUND_ERROR';\n _lastKnownPosition: any;\n _userLocationDotMarker: Marker;\n _accuracyCircleMarker: Marker;\n _accuracy: number;\n _setup: boolean; // set to true once the control has been setup\n\n /**\n * @param options - the control's options\n */\n constructor(options: GeolocateControlOptions) {\n super();\n this.options = extend({}, defaultOptions, options);\n }\n\n /** {@inheritDoc IControl.onAdd} */\n onAdd(map: Map) {\n this._map = map;\n this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');\n this._setupUI();\n checkGeolocationSupport().then((supported) => this._finishSetupUI(supported));\n return this._container;\n }\n\n /** {@inheritDoc IControl.onRemove} */\n onRemove() {\n // clear the geolocation watch if exists\n if (this._geolocationWatchID !== undefined) {\n window.navigator.geolocation.clearWatch(this._geolocationWatchID);\n this._geolocationWatchID = undefined;\n }\n\n // clear the markers from the map\n if (this.options.showUserLocation && this._userLocationDotMarker) {\n this._userLocationDotMarker.remove();\n }\n if (this.options.showAccuracyCircle && this._accuracyCircleMarker) {\n this._accuracyCircleMarker.remove();\n }\n\n DOM.remove(this._container);\n this._map.off('zoom', this._onZoom);\n this._map = undefined;\n numberOfWatches = 0;\n noTimeout = false;\n }\n\n /**\n * Check if the Geolocation API Position is outside the map's `maxBounds`.\n *\n * @param position - the Geolocation API Position\n * @returns `true` if position is outside the map's `maxBounds`, otherwise returns `false`.\n */\n _isOutOfMapMaxBounds(position: GeolocationPosition) {\n const bounds = this._map.getMaxBounds();\n const coordinates = position.coords;\n\n return bounds && (\n coordinates.longitude < bounds.getWest() ||\n coordinates.longitude > bounds.getEast() ||\n coordinates.latitude < bounds.getSouth() ||\n coordinates.latitude > bounds.getNorth()\n );\n }\n\n _setErrorState() {\n switch (this._watchState) {\n case 'WAITING_ACTIVE':\n this._watchState = 'ACTIVE_ERROR';\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error');\n break;\n case 'ACTIVE_LOCK':\n this._watchState = 'ACTIVE_ERROR';\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting');\n // turn marker grey\n break;\n case 'BACKGROUND':\n this._watchState = 'BACKGROUND_ERROR';\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background');\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background-error');\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting');\n // turn marker grey\n break;\n case 'ACTIVE_ERROR':\n break;\n default:\n throw new Error(`Unexpected watchState ${this._watchState}`);\n }\n }\n\n /**\n * When the Geolocation API returns a new location, update the `GeolocateControl`.\n *\n * @param position - the Geolocation API Position\n */\n _onSuccess = (position: GeolocationPosition) => {\n if (!this._map) {\n // control has since been removed\n return;\n }\n\n if (this._isOutOfMapMaxBounds(position)) {\n this._setErrorState();\n\n this.fire(new Event('outofmaxbounds', position));\n this._updateMarker();\n this._finish();\n\n return;\n }\n\n if (this.options.trackUserLocation) {\n // keep a record of the position so that if the state is BACKGROUND and the user\n // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for\n // watchPosition to trigger _onSuccess\n this._lastKnownPosition = position;\n\n switch (this._watchState) {\n case 'WAITING_ACTIVE':\n case 'ACTIVE_LOCK':\n case 'ACTIVE_ERROR':\n this._watchState = 'ACTIVE_LOCK';\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active');\n break;\n case 'BACKGROUND':\n case 'BACKGROUND_ERROR':\n this._watchState = 'BACKGROUND';\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error');\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background');\n break;\n default:\n throw new Error(`Unexpected watchState ${this._watchState}`);\n }\n }\n\n // if showUserLocation and the watch state isn't off then update the marker location\n if (this.options.showUserLocation && this._watchState !== 'OFF') {\n this._updateMarker(position);\n }\n\n // if in normal mode (not watch mode), or if in watch mode and the state is active watch\n // then update the camera\n if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') {\n this._updateCamera(position);\n }\n\n if (this.options.showUserLocation) {\n this._dotElement.classList.remove('maplibregl-user-location-dot-stale');\n }\n\n this.fire(new Event('geolocate', position));\n this._finish();\n };\n\n /**\n * Update the camera location to center on the current position\n *\n * @param position - the Geolocation API Position\n */\n _updateCamera = (position: GeolocationPosition) => {\n const center = new LngLat(position.coords.longitude, position.coords.latitude);\n const radius = position.coords.accuracy;\n const bearing = this._map.getBearing();\n const options = extend({bearing}, this.options.fitBoundsOptions);\n const newBounds = LngLatBounds.fromLngLat(center, radius);\n\n this._map.fitBounds(newBounds, options, {\n geolocateSource: true // tag this camera change so it won't cause the control to change to background state\n });\n };\n\n /**\n * Update the user location dot Marker to the current position\n *\n * @param position - the Geolocation API Position\n */\n _updateMarker = (position?: GeolocationPosition | null) => {\n if (position) {\n const center = new LngLat(position.coords.longitude, position.coords.latitude);\n this._accuracyCircleMarker.setLngLat(center).addTo(this._map);\n this._userLocationDotMarker.setLngLat(center).addTo(this._map);\n this._accuracy = position.coords.accuracy;\n if (this.options.showUserLocation && this.options.showAccuracyCircle) {\n this._updateCircleRadius();\n }\n } else {\n this._userLocationDotMarker.remove();\n this._accuracyCircleMarker.remove();\n }\n };\n\n _updateCircleRadius() {\n const bounds = this._map.getBounds();\n const southEastPoint = bounds.getSouthEast();\n const northEastPoint = bounds.getNorthEast();\n const mapHeightInMeters = southEastPoint.distanceTo(northEastPoint);\n const mapHeightInPixels = this._map._container.clientHeight;\n const circleDiameter = Math.ceil(2 * (this._accuracy / (mapHeightInMeters / mapHeightInPixels)));\n this._circleElement.style.width = `${circleDiameter}px`;\n this._circleElement.style.height = `${circleDiameter}px`;\n }\n\n _onZoom = () => {\n if (this.options.showUserLocation && this.options.showAccuracyCircle) {\n this._updateCircleRadius();\n }\n };\n\n _onError = (error: GeolocationPositionError) => {\n if (!this._map) {\n // control has since been removed\n return;\n }\n\n if (this.options.trackUserLocation) {\n if (error.code === 1) {\n // PERMISSION_DENIED\n this._watchState = 'OFF';\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error');\n this._geolocateButton.disabled = true;\n const title = this._map._getUIString('GeolocateControl.LocationNotAvailable');\n this._geolocateButton.title = title;\n this._geolocateButton.setAttribute('aria-label', title);\n\n if (this._geolocationWatchID !== undefined) {\n this._clearWatch();\n }\n } else if (error.code === 3 && noTimeout) {\n // this represents a forced error state\n // this was triggered to force immediate geolocation when a watch is already present\n // see https://github.com/mapbox/mapbox-gl-js/issues/8214\n // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position\n return;\n } else {\n this._setErrorState();\n }\n }\n\n if (this._watchState !== 'OFF' && this.options.showUserLocation) {\n this._dotElement.classList.add('maplibregl-user-location-dot-stale');\n }\n\n this.fire(new Event('error', error));\n\n this._finish();\n };\n\n _finish = () => {\n if (this._timeoutId) { clearTimeout(this._timeoutId); }\n this._timeoutId = undefined;\n };\n\n _setupUI = () => {\n // the control could have been removed before reaching here\n if (!this._map) {\n return;\n }\n\n this._container.addEventListener('contextmenu', (e: MouseEvent) => e.preventDefault());\n this._geolocateButton = DOM.create('button', 'maplibregl-ctrl-geolocate', this._container);\n DOM.create('span', 'maplibregl-ctrl-icon', this._geolocateButton).setAttribute('aria-hidden', 'true');\n this._geolocateButton.type = 'button';\n this._geolocateButton.disabled = true;\n };\n\n _finishSetupUI = (supported: boolean) => {\n // this method is called asynchronously during onAdd\n if (!this._map) {\n // control has since been removed\n return;\n }\n\n if (supported === false) {\n warnOnce('Geolocation support is not available so the GeolocateControl will be disabled.');\n const title = this._map._getUIString('GeolocateControl.LocationNotAvailable');\n this._geolocateButton.disabled = true;\n this._geolocateButton.title = title;\n this._geolocateButton.setAttribute('aria-label', title);\n } else {\n const title = this._map._getUIString('GeolocateControl.FindMyLocation');\n this._geolocateButton.disabled = false;\n this._geolocateButton.title = title;\n this._geolocateButton.setAttribute('aria-label', title);\n }\n\n if (this.options.trackUserLocation) {\n this._geolocateButton.setAttribute('aria-pressed', 'false');\n this._watchState = 'OFF';\n }\n\n // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map\n if (this.options.showUserLocation) {\n this._dotElement = DOM.create('div', 'maplibregl-user-location-dot');\n\n this._userLocationDotMarker = new Marker({element: this._dotElement});\n\n this._circleElement = DOM.create('div', 'maplibregl-user-location-accuracy-circle');\n this._accuracyCircleMarker = new Marker({element: this._circleElement, pitchAlignment: 'map'});\n\n if (this.options.trackUserLocation) this._watchState = 'OFF';\n\n this._map.on('zoom', this._onZoom);\n }\n\n this._geolocateButton.addEventListener('click', () => this.trigger());\n\n this._setup = true;\n\n // when the camera is changed (and it's not as a result of the Geolocation Control) change\n // the watch mode to background watch, so that the marker is updated but not the camera.\n if (this.options.trackUserLocation) {\n this._map.on('movestart', (event: any) => {\n const fromResize = event.originalEvent && event.originalEvent.type === 'resize';\n if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize) {\n this._watchState = 'BACKGROUND';\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n\n this.fire(new Event('trackuserlocationend'));\n this.fire(new Event('userlocationlostfocus'));\n }\n });\n }\n };\n\n /**\n * Programmatically request and move the map to the user's location.\n *\n * @returns `false` if called before control was added to a map, otherwise returns `true`.\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * map.on('load', () => {\n * geolocate.trigger();\n * });\n * ```\n */\n trigger(): boolean {\n if (!this._setup) {\n warnOnce('Geolocate control triggered before added to a map');\n return false;\n }\n if (this.options.trackUserLocation) {\n // update watchState and do any outgoing state cleanup\n switch (this._watchState) {\n case 'OFF':\n // turn on the Geolocate Control\n this._watchState = 'WAITING_ACTIVE';\n\n this.fire(new Event('trackuserlocationstart'));\n break;\n case 'WAITING_ACTIVE':\n case 'ACTIVE_LOCK':\n case 'ACTIVE_ERROR':\n case 'BACKGROUND_ERROR':\n // turn off the Geolocate Control\n numberOfWatches--;\n noTimeout = false;\n this._watchState = 'OFF';\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background');\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error');\n\n this.fire(new Event('trackuserlocationend'));\n break;\n case 'BACKGROUND':\n this._watchState = 'ACTIVE_LOCK';\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background');\n // set camera to last known location\n if (this._lastKnownPosition) this._updateCamera(this._lastKnownPosition);\n\n this.fire(new Event('trackuserlocationstart'));\n this.fire(new Event('userlocationfocus'));\n break;\n default:\n throw new Error(`Unexpected watchState ${this._watchState}`);\n }\n\n // incoming state setup\n switch (this._watchState) {\n case 'WAITING_ACTIVE':\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active');\n break;\n case 'ACTIVE_LOCK':\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active');\n break;\n case 'OFF':\n break;\n default:\n throw new Error(`Unexpected watchState ${this._watchState}`);\n }\n\n // manage geolocation.watchPosition / geolocation.clearWatch\n if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) {\n // clear watchPosition as we've changed to an OFF state\n this._clearWatch();\n } else if (this._geolocationWatchID === undefined) {\n // enable watchPosition since watchState is not OFF and there is no watchPosition already running\n\n this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting');\n this._geolocateButton.setAttribute('aria-pressed', 'true');\n\n numberOfWatches++;\n let positionOptions;\n if (numberOfWatches > 1) {\n positionOptions = {maximumAge: 600000, timeout: 0};\n noTimeout = true;\n } else {\n positionOptions = this.options.positionOptions;\n noTimeout = false;\n }\n\n this._geolocationWatchID = window.navigator.geolocation.watchPosition(\n this._onSuccess, this._onError, positionOptions);\n }\n } else {\n window.navigator.geolocation.getCurrentPosition(\n this._onSuccess, this._onError, this.options.positionOptions);\n\n // This timeout ensures that we still call finish() even if\n // the user declines to share their location in Firefox\n this._timeoutId = setTimeout(this._finish, 10000 /* 10sec */);\n }\n\n return true;\n }\n\n _clearWatch() {\n window.navigator.geolocation.clearWatch(this._geolocationWatchID);\n\n this._geolocationWatchID = undefined;\n this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n this._geolocateButton.setAttribute('aria-pressed', 'false');\n\n if (this.options.showUserLocation) {\n this._updateMarker(null);\n }\n }\n}\n\n","import {DOM} from '../../util/dom';\n\nimport type {Map} from '../map';\nimport type {ControlPosition, IControl} from './control';\n\n/**\n * The unit type for length to use for the {@link ScaleControl}\n */\nexport type Unit = 'imperial' | 'metric' | 'nautical';\n\n/**\n * The {@link ScaleControl} options object\n */\ntype ScaleControlOptions = {\n /**\n * The maximum length of the scale control in pixels.\n * @defaultValue 100\n */\n maxWidth?: number;\n /**\n * Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).\n * @defaultValue 'metric'\n */\n unit?: Unit;\n};\n\nconst defaultOptions: ScaleControlOptions = {\n maxWidth: 100,\n unit: 'metric'\n};\n\n/**\n * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground.\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * let scale = new ScaleControl({\n * maxWidth: 80,\n * unit: 'imperial'\n * });\n * map.addControl(scale);\n *\n * scale.setUnit('metric');\n * ```\n */\nexport class ScaleControl implements IControl {\n _map: Map;\n _container: HTMLElement;\n options: ScaleControlOptions;\n\n /**\n * @param options - the control's options\n */\n constructor(options?: ScaleControlOptions) {\n this.options = {...defaultOptions, ...options};\n }\n\n getDefaultPosition(): ControlPosition {\n return 'bottom-left';\n }\n\n _onMove = () => {\n updateScale(this._map, this._container, this.options);\n };\n\n /** {@inheritDoc IControl.onAdd} */\n onAdd(map: Map) {\n this._map = map;\n this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-scale', map.getContainer());\n\n this._map.on('move', this._onMove);\n this._onMove();\n\n return this._container;\n }\n\n /** {@inheritDoc IControl.onRemove} */\n onRemove() {\n DOM.remove(this._container);\n this._map.off('move', this._onMove);\n this._map = undefined;\n }\n\n /**\n * Set the scale's unit of the distance\n *\n * @param unit - Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).\n */\n setUnit = (unit: Unit) => {\n this.options.unit = unit;\n updateScale(this._map, this._container, this.options);\n };\n}\n\nfunction updateScale(map, container, options) {\n // A horizontal scale is imagined to be present at center of the map\n // container with maximum length (Default) as 100px.\n // Using spherical law of cosines approximation, the real distance is\n // found between the two coordinates.\n const maxWidth = options && options.maxWidth || 100;\n\n const y = map._container.clientHeight / 2;\n const left = map.unproject([0, y]);\n const right = map.unproject([maxWidth, y]);\n const maxMeters = left.distanceTo(right);\n // The real distance corresponding to 100px scale length is rounded off to\n // near pretty number and the scale length for the same is found out.\n // Default unit of the scale is based on User's locale.\n if (options && options.unit === 'imperial') {\n const maxFeet = 3.2808 * maxMeters;\n if (maxFeet > 5280) {\n const maxMiles = maxFeet / 5280;\n setScale(container, maxWidth, maxMiles, map._getUIString('ScaleControl.Miles'));\n } else {\n setScale(container, maxWidth, maxFeet, map._getUIString('ScaleControl.Feet'));\n }\n } else if (options && options.unit === 'nautical') {\n const maxNauticals = maxMeters / 1852;\n setScale(container, maxWidth, maxNauticals, map._getUIString('ScaleControl.NauticalMiles'));\n } else if (maxMeters >= 1000) {\n setScale(container, maxWidth, maxMeters / 1000, map._getUIString('ScaleControl.Kilometers'));\n } else {\n setScale(container, maxWidth, maxMeters, map._getUIString('ScaleControl.Meters'));\n }\n}\n\nfunction setScale(container, maxWidth, maxDistance, unit) {\n const distance = getRoundNum(maxDistance);\n const ratio = distance / maxDistance;\n container.style.width = `${maxWidth * ratio}px`;\n container.innerHTML = `${distance} ${unit}`;\n}\n\nfunction getDecimalRoundNum(d) {\n const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10));\n return Math.round(d * multiplier) / multiplier;\n}\n\nfunction getRoundNum(num) {\n const pow10 = Math.pow(10, (`${Math.floor(num)}`).length - 1);\n let d = num / pow10;\n\n d = d >= 10 ? 10 :\n d >= 5 ? 5 :\n d >= 3 ? 3 :\n d >= 2 ? 2 :\n d >= 1 ? 1 : getDecimalRoundNum(d);\n\n return pow10 * d;\n}\n","import {extend} from '../util/util';\nimport {Event, Evented} from '../util/evented';\nimport {MapMouseEvent} from '../ui/events';\nimport {DOM} from '../util/dom';\nimport {LngLat} from '../geo/lng_lat';\nimport Point from '@mapbox/point-geometry';\nimport {smartWrap} from '../util/smart_wrap';\nimport {anchorTranslate, applyAnchorClass} from './anchor';\n\nimport type {PositionAnchor} from './anchor';\nimport type {Map} from './map';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport type {PointLike} from './camera';\n\nconst defaultOptions = {\n closeButton: true,\n closeOnClick: true,\n focusAfterOpen: true,\n className: '',\n maxWidth: '240px',\n subpixelPositioning: false\n};\n\n/**\n * A pixel offset specified as:\n *\n * - a single number specifying a distance from the location\n * - a {@link PointLike} specifying a constant offset\n * - an object of {@link Point}s specifying an offset for each anchor position\n *\n * Negative offsets indicate left and up.\n */\nexport type Offset = number | PointLike | {\n [_ in PositionAnchor]: PointLike;\n};\n\n/**\n * The {@link Popup} options object\n */\nexport type PopupOptions = {\n /**\n * If `true`, a close button will appear in the top right corner of the popup.\n * @defaultValue true\n */\n closeButton?: boolean;\n /**\n * If `true`, the popup will closed when the map is clicked.\n * @defaultValue true\n */\n closeOnClick?: boolean;\n /**\n * If `true`, the popup will closed when the map moves.\n * @defaultValue false\n */\n closeOnMove?: boolean;\n /**\n * If `true`, the popup will try to focus the first focusable element inside the popup.\n * @defaultValue true\n */\n focusAfterOpen?: boolean;\n /**\n * A string indicating the part of the Popup that should\n * be positioned closest to the coordinate set via {@link Popup#setLngLat}.\n * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`,\n * `'top-right'`, `'bottom-left'`, and `'bottom-right'`. If unset the anchor will be\n * dynamically set to ensure the popup falls within the map container with a preference\n * for `'bottom'`.\n */\n anchor?: PositionAnchor;\n /**\n * A pixel offset applied to the popup's location\n */\n offset?: Offset;\n /**\n * Space-separated CSS class names to add to popup container\n */\n className?: string;\n /**\n * A string that sets the CSS property of the popup's maximum width, eg `'300px'`.\n * To ensure the popup resizes to fit its content, set this property to `'none'`.\n * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width\n * @defaultValue '240px'\n */\n maxWidth?: string;\n /**\n * If `true`, rounding is disabled for placement of the popup, allowing for\n * subpixel positioning and smoother movement when the popup is translated.\n * @defaultValue false\n */\n subpixelPositioning?: boolean;\n};\n\nconst focusQuerySelector = [\n 'a[href]',\n '[tabindex]:not([tabindex=\\'-1\\'])',\n '[contenteditable]:not([contenteditable=\\'false\\'])',\n 'button:not([disabled])',\n 'input:not([disabled])',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n].join(', ');\n\n/**\n * A popup component.\n *\n * @group Markers and Controls\n *\n *\n * @example\n * Create a popup\n * ```ts\n * let popup = new Popup();\n * // Set an event listener that will fire\n * // any time the popup is opened\n * popup.on('open', () => {\n * console.log('popup was opened');\n * });\n * ```\n *\n * @example\n * Create a popup\n * ```ts\n * let popup = new Popup();\n * // Set an event listener that will fire\n * // any time the popup is closed\n * popup.on('close', () => {\n * console.log('popup was closed');\n * });\n * ```\n *\n * @example\n * ```ts\n * let markerHeight = 50, markerRadius = 10, linearOffset = 25;\n * let popupOffsets = {\n * 'top': [0, 0],\n * 'top-left': [0,0],\n * 'top-right': [0,0],\n * 'bottom': [0, -markerHeight],\n * 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n * 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n * 'left': [markerRadius, (markerHeight - markerRadius) * -1],\n * 'right': [-markerRadius, (markerHeight - markerRadius) * -1]\n * };\n * let popup = new Popup({offset: popupOffsets, className: 'my-class'})\n * .setLngLat(e.lngLat)\n * .setHTML(\"

Hello World!

\")\n * .setMaxWidth(\"300px\")\n * .addTo(map);\n * ```\n * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/)\n * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/)\n * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/)\n * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/)\n *\n * ## Events\n *\n * **Event** `open` of type {@link Event} will be fired when the popup is opened manually or programmatically.\n *\n * **Event** `close` of type {@link Event} will be fired when the popup is closed manually or programmatically.\n */\nexport class Popup extends Evented {\n _map: Map;\n options: PopupOptions;\n _content: HTMLElement;\n _container: HTMLElement;\n _closeButton: HTMLButtonElement;\n _tip: HTMLElement;\n _lngLat: LngLat;\n _trackPointer: boolean;\n _pos: Point;\n _flatPos: Point;\n\n /**\n * @param options - the options\n */\n constructor(options?: PopupOptions) {\n super();\n this.options = extend(Object.create(defaultOptions), options);\n }\n\n /**\n * Adds the popup to a map.\n *\n * @param map - The MapLibre GL JS map to add the popup to.\n * @example\n * ```ts\n * new Popup()\n * .setLngLat([0, 0])\n * .setHTML(\"

Null Island

\")\n * .addTo(map);\n * ```\n * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/)\n * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/)\n * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/)\n * @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/polygon-popup-on-click/)\n */\n addTo(map: Map): this {\n if (this._map) this.remove();\n\n this._map = map;\n if (this.options.closeOnClick) {\n this._map.on('click', this._onClose);\n }\n\n if (this.options.closeOnMove) {\n this._map.on('move', this._onClose);\n }\n\n this._map.on('remove', this.remove);\n this._update();\n this._focusFirstElement();\n\n if (this._trackPointer) {\n this._map.on('mousemove', this._onMouseMove);\n this._map.on('mouseup', this._onMouseUp);\n if (this._container) {\n this._container.classList.add('maplibregl-popup-track-pointer');\n }\n this._map._canvasContainer.classList.add('maplibregl-track-pointer');\n } else {\n this._map.on('move', this._update);\n }\n\n this.fire(new Event('open'));\n\n return this;\n }\n\n /**\n * @returns `true` if the popup is open, `false` if it is closed.\n */\n isOpen() {\n return !!this._map;\n }\n\n /**\n * Removes the popup from the map it has been added to.\n *\n * @example\n * ```ts\n * let popup = new Popup().addTo(map);\n * popup.remove();\n * ```\n */\n remove = (): this => {\n if (this._content) {\n DOM.remove(this._content);\n }\n\n if (this._container) {\n DOM.remove(this._container);\n delete this._container;\n }\n\n if (this._map) {\n this._map.off('move', this._update);\n this._map.off('move', this._onClose);\n this._map.off('click', this._onClose);\n this._map.off('remove', this.remove);\n this._map.off('mousemove', this._onMouseMove);\n this._map.off('mouseup', this._onMouseUp);\n this._map.off('drag', this._onDrag);\n this._map._canvasContainer.classList.remove('maplibregl-track-pointer');\n delete this._map;\n this.fire(new Event('close'));\n }\n\n return this;\n };\n\n /**\n * Returns the geographical location of the popup's anchor.\n *\n * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously\n * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep\n * the popup on screen.\n *\n * @returns The geographical location of the popup's anchor.\n */\n getLngLat(): LngLat {\n return this._lngLat;\n }\n\n /**\n * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior.\n *\n * @param lnglat - The geographical location to set as the popup's anchor.\n */\n setLngLat(lnglat: LngLatLike): this {\n this._lngLat = LngLat.convert(lnglat);\n this._pos = null;\n this._flatPos = null;\n\n this._trackPointer = false;\n\n this._update();\n\n if (this._map) {\n this._map.on('move', this._update);\n this._map.off('mousemove', this._onMouseMove);\n if (this._container) {\n this._container.classList.remove('maplibregl-popup-track-pointer');\n }\n this._map._canvasContainer.classList.remove('maplibregl-track-pointer');\n }\n\n return this;\n }\n\n /**\n * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior.\n * For most use cases, set `closeOnClick` and `closeButton` to `false`.\n * @example\n * ```ts\n * let popup = new Popup({ closeOnClick: false, closeButton: false })\n * .setHTML(\"

Hello World!

\")\n * .trackPointer()\n * .addTo(map);\n * ```\n */\n trackPointer(): this {\n this._trackPointer = true;\n this._pos = null;\n this._flatPos = null;\n this._update();\n if (this._map) {\n this._map.off('move', this._update);\n this._map.on('mousemove', this._onMouseMove);\n this._map.on('drag', this._onDrag);\n if (this._container) {\n this._container.classList.add('maplibregl-popup-track-pointer');\n }\n this._map._canvasContainer.classList.add('maplibregl-track-pointer');\n }\n\n return this;\n\n }\n\n /**\n * Returns the `Popup`'s HTML element.\n * @example\n * Change the `Popup` element's font size\n * ```ts\n * let popup = new Popup()\n * .setLngLat([-96, 37.8])\n * .setHTML(\"

Hello World!

\")\n * .addTo(map);\n * let popupElem = popup.getElement();\n * popupElem.style.fontSize = \"25px\";\n * ```\n * @returns element\n */\n getElement(): HTMLElement {\n return this._container;\n }\n\n /**\n * Sets the popup's content to a string of text.\n *\n * This function creates a [Text](https://developer.mozilla.org/en-US/docs/Web/API/Text) node in the DOM,\n * so it cannot insert raw HTML. Use this method for security against XSS\n * if the popup content is user-provided.\n *\n * @param text - Textual content for the popup.\n * @example\n * ```ts\n * let popup = new Popup()\n * .setLngLat(e.lngLat)\n * .setText('Hello, world!')\n * .addTo(map);\n * ```\n */\n setText(text: string): this {\n return this.setDOMContent(document.createTextNode(text));\n }\n\n /**\n * Sets the popup's content to the HTML provided as a string.\n *\n * This method does not perform HTML filtering or sanitization, and must be\n * used only with trusted content. Consider {@link Popup#setText} if\n * the content is an untrusted text string.\n *\n * @param html - A string representing HTML content for the popup.\n * @example\n * ```ts\n * let popup = new Popup()\n * .setLngLat(e.lngLat)\n * .setHTML(\"

Hello World!

\")\n * .addTo(map);\n * ```\n * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/)\n * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/)\n * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/)\n * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/)\n */\n setHTML(html: string): this {\n const frag = document.createDocumentFragment();\n const temp = document.createElement('body');\n let child;\n temp.innerHTML = html;\n while (true) {\n child = temp.firstChild;\n if (!child) break;\n frag.appendChild(child);\n }\n\n return this.setDOMContent(frag);\n }\n\n /**\n * Returns the popup's maximum width.\n *\n * @returns The maximum width of the popup.\n */\n getMaxWidth(): string {\n return this._container?.style.maxWidth;\n }\n\n /**\n * Sets the popup's maximum width. This is setting the CSS property `max-width`.\n * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width\n *\n * @param maxWidth - A string representing the value for the maximum width.\n */\n setMaxWidth(maxWidth: string): this {\n this.options.maxWidth = maxWidth;\n this._update();\n return this;\n }\n\n /**\n * Sets the popup's content to the element provided as a DOM node.\n *\n * @param htmlNode - A DOM node to be used as content for the popup.\n * @example\n * Create an element with the popup content\n * ```ts\n * let div = document.createElement('div');\n * div.innerHTML = 'Hello, world!';\n * let popup = new Popup()\n * .setLngLat(e.lngLat)\n * .setDOMContent(div)\n * .addTo(map);\n * ```\n */\n setDOMContent(htmlNode: Node): this {\n if (this._content) {\n // Clear out children first.\n while (this._content.hasChildNodes()) {\n if (this._content.firstChild) {\n this._content.removeChild(this._content.firstChild);\n }\n }\n } else {\n this._content = DOM.create('div', 'maplibregl-popup-content', this._container);\n }\n\n // The close button should be the last tabbable element inside the popup for a good keyboard UX.\n this._content.appendChild(htmlNode);\n this._createCloseButton();\n this._update();\n this._focusFirstElement();\n return this;\n }\n\n /**\n * Adds a CSS class to the popup container element.\n *\n * @param className - Non-empty string with CSS class name to add to popup container\n *\n * @example\n * ```ts\n * let popup = new Popup()\n * popup.addClassName('some-class')\n * ```\n */\n addClassName(className: string) {\n if (this._container) {\n this._container.classList.add(className);\n }\n return this;\n }\n\n /**\n * Removes a CSS class from the popup container element.\n *\n * @param className - Non-empty string with CSS class name to remove from popup container\n *\n * @example\n * ```ts\n * let popup = new Popup()\n * popup.removeClassName('some-class')\n * ```\n */\n removeClassName(className: string) {\n if (this._container) {\n this._container.classList.remove(className);\n }\n return this;\n }\n\n /**\n * Sets the popup's offset.\n *\n * @param offset - Sets the popup's offset.\n */\n setOffset (offset?: Offset): this {\n this.options.offset = offset;\n this._update();\n return this;\n }\n\n /**\n * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class.\n *\n * @param className - Non-empty string with CSS class name to add/remove\n *\n * @returns if the class was removed return false, if class was added, then return true, undefined if there is no container\n *\n * @example\n * ```ts\n * let popup = new Popup()\n * popup.toggleClassName('toggleClass')\n * ```\n */\n toggleClassName(className: string): boolean | undefined {\n if (this._container) {\n return this._container.classList.toggle(className);\n }\n }\n\n /**\n * Set the option to allow subpixel positioning of the popup by passing a boolean\n *\n * @param value - When boolean is true, subpixel positioning is enabled for the popup.\n *\n * @example\n * ```ts\n * let popup = new Popup()\n * popup.setSubpixelPositioning(true);\n * ```\n */\n setSubpixelPositioning(value: boolean) {\n this.options.subpixelPositioning = value;\n }\n\n _createCloseButton() {\n if (this.options.closeButton) {\n this._closeButton = DOM.create('button', 'maplibregl-popup-close-button', this._content);\n this._closeButton.type = 'button';\n this._closeButton.innerHTML = '×';\n this._closeButton.addEventListener('click', this._onClose);\n }\n }\n\n _onMouseUp = (event: MapMouseEvent) => {\n this._update(event.point);\n };\n\n _onMouseMove = (event: MapMouseEvent) => {\n this._update(event.point);\n };\n\n _onDrag = (event: MapMouseEvent) => {\n this._update(event.point);\n };\n\n _update = (cursor?: Point) => {\n const hasPosition = this._lngLat || this._trackPointer;\n\n if (!this._map || !hasPosition || !this._content) { return; }\n\n if (!this._container) {\n this._container = DOM.create('div', 'maplibregl-popup', this._map.getContainer());\n this._tip = DOM.create('div', 'maplibregl-popup-tip', this._container);\n this._container.appendChild(this._content);\n if (this.options.className) {\n for (const name of this.options.className.split(' ')) {\n this._container.classList.add(name);\n }\n }\n\n if (this._closeButton) {\n this._closeButton.setAttribute('aria-label', this._map._getUIString('Popup.Close'));\n }\n\n if (this._trackPointer) {\n this._container.classList.add('maplibregl-popup-track-pointer');\n }\n }\n\n if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) {\n this._container.style.maxWidth = this.options.maxWidth;\n }\n\n if (this._map.transform.renderWorldCopies && !this._trackPointer) {\n this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform);\n } else {\n this._lngLat = this._lngLat?.wrap();\n }\n\n if (this._trackPointer && !cursor) return;\n\n const pos = this._flatPos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat);\n if (this._map.terrain) {\n // flat position is saved because smartWrap needs non-elevated points\n this._flatPos = this._trackPointer && cursor ? cursor : this._map.transform.locationPoint(this._lngLat);\n }\n\n let anchor = this.options.anchor;\n const offset = normalizeOffset(this.options.offset);\n\n if (!anchor) {\n const width = this._container.offsetWidth;\n const height = this._container.offsetHeight;\n let anchorComponents;\n\n if (pos.y + offset.bottom.y < height) {\n anchorComponents = ['top'];\n } else if (pos.y > this._map.transform.height - height) {\n anchorComponents = ['bottom'];\n } else {\n anchorComponents = [];\n }\n\n if (pos.x < width / 2) {\n anchorComponents.push('left');\n } else if (pos.x > this._map.transform.width - width / 2) {\n anchorComponents.push('right');\n }\n\n if (anchorComponents.length === 0) {\n anchor = 'bottom';\n } else {\n anchor = (anchorComponents.join('-') as any);\n }\n }\n\n let offsetedPos = pos.add(offset[anchor]);\n\n if (!this.options.subpixelPositioning) {\n offsetedPos = offsetedPos.round();\n }\n\n DOM.setTransform(this._container, `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`);\n applyAnchorClass(this._container, anchor, 'popup');\n };\n\n _focusFirstElement() {\n if (!this.options.focusAfterOpen || !this._container) return;\n\n const firstFocusable = this._container.querySelector(focusQuerySelector) as HTMLElement;\n\n if (firstFocusable) firstFocusable.focus();\n }\n\n _onClose = () => {\n this.remove();\n };\n}\n\nfunction normalizeOffset(offset?: Offset | null) {\n if (!offset) {\n return normalizeOffset(new Point(0, 0));\n\n } else if (typeof offset === 'number') {\n // input specifies a radius from which to calculate offsets at all positions\n const cornerOffset = Math.round(Math.abs(offset) / Math.SQRT2);\n return {\n 'center': new Point(0, 0),\n 'top': new Point(0, offset),\n 'top-left': new Point(cornerOffset, cornerOffset),\n 'top-right': new Point(-cornerOffset, cornerOffset),\n 'bottom': new Point(0, -offset),\n 'bottom-left': new Point(cornerOffset, -cornerOffset),\n 'bottom-right': new Point(-cornerOffset, -cornerOffset),\n 'left': new Point(offset, 0),\n 'right': new Point(-offset, 0)\n };\n\n } else if (offset instanceof Point || Array.isArray(offset)) {\n // input specifies a single offset to be applied to all positions\n const convertedOffset = Point.convert(offset);\n return {\n 'center': convertedOffset,\n 'top': convertedOffset,\n 'top-left': convertedOffset,\n 'top-right': convertedOffset,\n 'bottom': convertedOffset,\n 'bottom-left': convertedOffset,\n 'bottom-right': convertedOffset,\n 'left': convertedOffset,\n 'right': convertedOffset\n };\n\n } else {\n // input specifies an offset per position\n return {\n 'center': Point.convert(offset['center'] || [0, 0]),\n 'top': Point.convert(offset['top'] || [0, 0]),\n 'top-left': Point.convert(offset['top-left'] || [0, 0]),\n 'top-right': Point.convert(offset['top-right'] || [0, 0]),\n 'bottom': Point.convert(offset['bottom'] || [0, 0]),\n 'bottom-left': Point.convert(offset['bottom-left'] || [0, 0]),\n 'bottom-right': Point.convert(offset['bottom-right'] || [0, 0]),\n 'left': Point.convert(offset['left'] || [0, 0]),\n 'right': Point.convert(offset['right'] || [0, 0])\n };\n }\n}\n","import packageJSON from '../package.json' with {type: 'json'};\nimport {Map} from './ui/map';\nimport {NavigationControl} from './ui/control/navigation_control';\nimport {GeolocateControl} from './ui/control/geolocate_control';\nimport {AttributionControl} from './ui/control/attribution_control';\nimport {LogoControl} from './ui/control/logo_control';\nimport {ScaleControl} from './ui/control/scale_control';\nimport {FullscreenControl} from './ui/control/fullscreen_control';\nimport {TerrainControl} from './ui/control/terrain_control';\nimport {Popup} from './ui/popup';\nimport {Marker} from './ui/marker';\nimport {Style} from './style/style';\nimport {LngLat, LngLatLike} from './geo/lng_lat';\nimport {LngLatBounds, LngLatBoundsLike} from './geo/lng_lat_bounds';\nimport Point from '@mapbox/point-geometry';\nimport {MercatorCoordinate} from './geo/mercator_coordinate';\nimport {Evented} from './util/evented';\nimport {config} from './util/config';\nimport {rtlMainThreadPluginFactory} from './source/rtl_text_plugin_main_thread';\nimport {WorkerPool} from './util/worker_pool';\nimport {prewarm, clearPrewarmedResources} from './util/global_worker_pool';\nimport {AJAXError} from './util/ajax';\nimport {GeoJSONSource} from './source/geojson_source';\nimport {CanvasSource, CanvasSourceSpecification} from './source/canvas_source';\nimport {ImageSource} from './source/image_source';\nimport {RasterDEMTileSource} from './source/raster_dem_tile_source';\nimport {RasterTileSource} from './source/raster_tile_source';\nimport {VectorTileSource} from './source/vector_tile_source';\nimport {VideoSource} from './source/video_source';\nimport {Source, addSourceType} from './source/source';\nimport {addProtocol, removeProtocol} from './source/protocol_crud';\nimport {getGlobalDispatcher} from './util/dispatcher';\nimport {IControl} from './ui/control/control';\nimport {EdgeInsets, PaddingOptions} from './geo/edge_insets';\nimport {MapTerrainEvent, MapStyleImageMissingEvent, MapStyleDataEvent, MapSourceDataEvent, MapLibreZoomEvent, MapLibreEvent, MapLayerTouchEvent, MapLayerMouseEvent, MapLayerEventType, MapEventType, MapDataEvent, MapContextEvent, MapWheelEvent, MapTouchEvent, MapMouseEvent} from './ui/events';\nimport {BoxZoomHandler} from './ui/handler/box_zoom';\nimport {DragRotateHandler} from './ui/handler/shim/drag_rotate';\nimport {DragPanHandler} from './ui/handler/shim/drag_pan';\nimport {ScrollZoomHandler} from './ui/handler/scroll_zoom';\nimport {TwoFingersTouchZoomRotateHandler} from './ui/handler/shim/two_fingers_touch';\nimport {CustomLayerInterface} from './style/style_layer/custom_style_layer';\nimport {PointLike} from './ui/camera';\nimport {Hash} from './ui/hash';\nimport {CooperativeGesturesHandler} from './ui/handler/cooperative_gestures';\nimport {DoubleClickZoomHandler} from './ui/handler/shim/dblclick_zoom';\nimport {KeyboardHandler} from './ui/handler/keyboard';\nimport {TwoFingersTouchPitchHandler, TwoFingersTouchRotateHandler, TwoFingersTouchZoomHandler} from './ui/handler/two_fingers_touch';\nimport {MessageType} from './util/actor_messages';\nconst version = packageJSON.version;\n\nexport type * from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text).\n * Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left.\n *\n * @param pluginURL - URL pointing to the Mapbox RTL text plugin source.\n * @param lazy - If set to `true`, maplibre will defer loading the plugin until rtl text is encountered,\n * rtl text will then be rendered only after the plugin finishes loading.\n * @example\n * ```ts\n * setRTLTextPlugin('https://unpkg.com/@mapbox/mapbox-gl-rtl-text@0.2.3/mapbox-gl-rtl-text.js', false);\n * ```\n * @see [Add support for right-to-left scripts](https://maplibre.org/maplibre-gl-js/docs/examples/mapbox-gl-rtl-text/)\n */\nfunction setRTLTextPlugin(pluginURL: string, lazy: boolean): Promise {\n return rtlMainThreadPluginFactory().setRTLTextPlugin(pluginURL, lazy);\n}\n/**\n * Gets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text) status.\n * The status can be `unavailable` (i.e. not requested or removed), `loading`, `loaded` or `error`.\n * If the status is `loaded` and the plugin is requested again, an error will be thrown.\n *\n * @example\n * ```ts\n * const pluginStatus = getRTLTextPluginStatus();\n * ```\n */\nfunction getRTLTextPluginStatus(): string {\n return rtlMainThreadPluginFactory().getRTLTextPluginStatus();\n}\n/**\n * Returns the package version of the library\n * @returns Package version of the library\n */\nfunction getVersion() { return version; }\n/**\n * Gets the number of web workers instantiated on a page with GL JS maps.\n * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3).\n * Make sure to set this property before creating any map instances for it to have effect.\n *\n * @returns Number of workers currently configured.\n * @example\n * ```ts\n * const workerCount = getWorkerCount()\n * ```\n */\nfunction getWorkerCount() { return WorkerPool.workerCount; }\n/**\n * Sets the number of web workers instantiated on a page with GL JS maps.\n * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3).\n * Make sure to set this property before creating any map instances for it to have effect.\n *\n * @example\n * ```ts\n * setWorkerCount(2);\n * ```\n */\nfunction setWorkerCount(count: number) { WorkerPool.workerCount = count; }\n/**\n * Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel,\n * which affects performance in raster-heavy maps. 16 by default.\n *\n * @returns Number of parallel requests currently configured.\n * @example\n * ```ts\n * getMaxParallelImageRequests();\n * ```\n */\nfunction getMaxParallelImageRequests() { return config.MAX_PARALLEL_IMAGE_REQUESTS; }\n/**\n * Sets the maximum number of images (raster tiles, sprites, icons) to load in parallel,\n * which affects performance in raster-heavy maps. 16 by default.\n *\n * @example\n * ```ts\n * setMaxParallelImageRequests(10);\n * ```\n */\nfunction setMaxParallelImageRequests(numRequests: number) { config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests; }\n/**\n * Gets the worker url\n * @returns The worker url\n */\nfunction getWorkerUrl() { return config.WORKER_URL; }\n/**\n * Sets the worker url\n */\nfunction setWorkerUrl(value: string) { config.WORKER_URL = value; }\n/**\n * Allows loading javascript code in the worker thread.\n * *Note* that since this is using some very internal classes and flows it is considered experimental and can break at any point.\n *\n * It can be useful for the following examples:\n * 1. Using `self.addProtocol` in the worker thread - note that you might need to also register the protocol on the main thread.\n * 2. Using `self.registerWorkerSource(workerSource: WorkerSource)` to register a worker source, which should come with `addSourceType` usually.\n * 3. using `self.actor.registerMessageHandler` to override some internal worker operations\n * @param workerUrl - the worker url e.g. a url of a javascript file to load in the worker\n * @returns\n *\n * @example\n * ```ts\n * // below is an example of sending a js file to the worker to load the method there\n * // Note that you'll need to call the global function `addProtocol` in the worker to register the protocol there.\n * // add-protocol-worker.js\n * async function loadFn(params, abortController) {\n * const t = await fetch(`https://${params.url.split(\"://\")[1]}`);\n * if (t.status == 200) {\n * const buffer = await t.arrayBuffer();\n * return {data: buffer}\n * } else {\n * throw new Error(`Tile fetch error: ${t.statusText}`);\n * }\n * }\n * self.addProtocol('custom', loadFn);\n *\n * // main.js\n * importScriptInWorkers('add-protocol-worker.js');\n * ```\n */\nfunction importScriptInWorkers(workerUrl: string) { return getGlobalDispatcher().broadcast(MessageType.importScript, workerUrl); }\n\nexport {\n Map,\n NavigationControl,\n GeolocateControl,\n AttributionControl,\n LogoControl,\n ScaleControl,\n FullscreenControl,\n TerrainControl,\n Hash,\n Popup,\n Marker,\n Style,\n LngLat,\n LngLatBounds,\n Point,\n MercatorCoordinate,\n Evented,\n AJAXError,\n config,\n CanvasSource,\n GeoJSONSource,\n ImageSource,\n RasterDEMTileSource,\n RasterTileSource,\n VectorTileSource,\n VideoSource,\n EdgeInsets,\n BoxZoomHandler,\n DragRotateHandler,\n DragPanHandler,\n ScrollZoomHandler,\n TwoFingersTouchZoomRotateHandler,\n CooperativeGesturesHandler,\n DoubleClickZoomHandler,\n KeyboardHandler,\n TwoFingersTouchZoomHandler,\n TwoFingersTouchRotateHandler,\n TwoFingersTouchPitchHandler,\n MapWheelEvent,\n MapTouchEvent,\n MapMouseEvent,\n type IControl,\n type CustomLayerInterface,\n type CanvasSourceSpecification,\n type PaddingOptions,\n type LngLatLike,\n type PointLike,\n type LngLatBoundsLike,\n type Source,\n type MapTerrainEvent,\n type MapStyleImageMissingEvent,\n type MapStyleDataEvent,\n type MapSourceDataEvent,\n type MapLibreZoomEvent,\n type MapLibreEvent,\n type MapLayerTouchEvent,\n type MapLayerMouseEvent,\n type MapLayerEventType,\n type MapEventType,\n type MapDataEvent,\n type MapContextEvent,\n setRTLTextPlugin,\n getRTLTextPluginStatus,\n prewarm,\n clearPrewarmedResources,\n getVersion,\n getWorkerCount,\n setWorkerCount,\n getMaxParallelImageRequests,\n setMaxParallelImageRequests,\n getWorkerUrl,\n setWorkerUrl,\n addProtocol,\n removeProtocol,\n addSourceType,\n importScriptInWorkers\n};\n","import {DOM} from '../../util/dom';\n\nimport {warnOnce} from '../../util/util';\n\nimport {Event, Evented} from '../../util/evented';\nimport type {Map} from '../map';\nimport type {IControl} from './control';\n\n/**\n * The {@link FullscreenControl} options object\n */\ntype FullscreenControlOptions = {\n /**\n * `container` is the [compatible DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen#Compatible_elements) which should be made full screen. By default, the map container element will be made full screen.\n */\n container?: HTMLElement;\n};\n\n/**\n * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode.\n * When [requestFullscreen](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen) is not supported, fullscreen is handled via CSS properties.\n * The map's `cooperativeGestures` option is temporarily disabled while the map\n * is in fullscreen mode, and is restored when the map exist fullscreen mode.\n *\n * @group Markers and Controls\n * @param options - the full screen control options\n *\n * @example\n * ```ts\n * map.addControl(new FullscreenControl({container: document.querySelector('body')}));\n * ```\n * @see [View a fullscreen map](https://maplibre.org/maplibre-gl-js/docs/examples/fullscreen/)\n *\n * ## Events\n *\n * **Event** `fullscreenstart` of type {@link Event} will be fired when fullscreen mode has started.\n *\n * **Event** `fullscreenend` of type {@link Event} will be fired when fullscreen mode has ended.\n */\nexport class FullscreenControl extends Evented implements IControl {\n _map: Map;\n _controlContainer: HTMLElement;\n _fullscreen: boolean;\n _fullscreenchange: string;\n _fullscreenButton: HTMLButtonElement;\n _container: HTMLElement;\n _prevCooperativeGesturesEnabled: boolean;\n\n /**\n * @param options - the control's options\n */\n constructor(options: FullscreenControlOptions = {}) {\n super();\n this._fullscreen = false;\n\n if (options && options.container) {\n if (options.container instanceof HTMLElement) {\n this._container = options.container;\n } else {\n warnOnce('Full screen control \\'container\\' must be a DOM element.');\n }\n }\n\n if ('onfullscreenchange' in document) {\n this._fullscreenchange = 'fullscreenchange';\n } else if ('onmozfullscreenchange' in document) {\n this._fullscreenchange = 'mozfullscreenchange';\n } else if ('onwebkitfullscreenchange' in document) {\n this._fullscreenchange = 'webkitfullscreenchange';\n } else if ('onmsfullscreenchange' in document) {\n this._fullscreenchange = 'MSFullscreenChange';\n }\n }\n\n /** {@inheritDoc IControl.onAdd} */\n onAdd(map: Map): HTMLElement {\n this._map = map;\n if (!this._container) this._container = this._map.getContainer();\n this._controlContainer = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');\n this._setupUI();\n return this._controlContainer;\n }\n\n /** {@inheritDoc IControl.onRemove} */\n onRemove() {\n DOM.remove(this._controlContainer);\n this._map = null;\n window.document.removeEventListener(this._fullscreenchange, this._onFullscreenChange);\n }\n\n _setupUI() {\n const button = this._fullscreenButton = DOM.create('button', (('maplibregl-ctrl-fullscreen')), this._controlContainer);\n DOM.create('span', 'maplibregl-ctrl-icon', button).setAttribute('aria-hidden', 'true');\n button.type = 'button';\n this._updateTitle();\n this._fullscreenButton.addEventListener('click', this._onClickFullscreen);\n window.document.addEventListener(this._fullscreenchange, this._onFullscreenChange);\n }\n\n _updateTitle() {\n const title = this._getTitle();\n this._fullscreenButton.setAttribute('aria-label', title);\n this._fullscreenButton.title = title;\n }\n\n _getTitle() {\n return this._map._getUIString(this._isFullscreen() ? 'FullscreenControl.Exit' : 'FullscreenControl.Enter');\n }\n\n _isFullscreen() {\n return this._fullscreen;\n }\n\n _onFullscreenChange = () => {\n let fullscreenElement =\n window.document.fullscreenElement ||\n (window.document as any).mozFullScreenElement ||\n (window.document as any).webkitFullscreenElement ||\n (window.document as any).msFullscreenElement;\n\n while (fullscreenElement?.shadowRoot?.fullscreenElement) {\n fullscreenElement = fullscreenElement.shadowRoot.fullscreenElement;\n }\n\n if ((fullscreenElement === this._container) !== this._fullscreen) {\n this._handleFullscreenChange();\n }\n };\n\n _handleFullscreenChange() {\n this._fullscreen = !this._fullscreen;\n this._fullscreenButton.classList.toggle('maplibregl-ctrl-shrink');\n this._fullscreenButton.classList.toggle('maplibregl-ctrl-fullscreen');\n this._updateTitle();\n\n if (this._fullscreen) {\n this.fire(new Event('fullscreenstart'));\n this._prevCooperativeGesturesEnabled = this._map.cooperativeGestures.isEnabled();\n this._map.cooperativeGestures.disable();\n } else {\n this.fire(new Event('fullscreenend'));\n if (this._prevCooperativeGesturesEnabled) {\n this._map.cooperativeGestures.enable();\n }\n }\n }\n\n _onClickFullscreen = () => {\n if (this._isFullscreen()) {\n this._exitFullscreen();\n } else {\n this._requestFullscreen();\n }\n };\n\n _exitFullscreen() {\n if (window.document.exitFullscreen) {\n (window.document as any).exitFullscreen();\n } else if ((window.document as any).mozCancelFullScreen) {\n (window.document as any).mozCancelFullScreen();\n } else if ((window.document as any).msExitFullscreen) {\n (window.document as any).msExitFullscreen();\n } else if ((window.document as any).webkitCancelFullScreen) {\n (window.document as any).webkitCancelFullScreen();\n } else {\n this._togglePseudoFullScreen();\n }\n }\n\n _requestFullscreen() {\n if (this._container.requestFullscreen) {\n this._container.requestFullscreen();\n } else if ((this._container as any).mozRequestFullScreen) {\n (this._container as any).mozRequestFullScreen();\n } else if ((this._container as any).msRequestFullscreen) {\n (this._container as any).msRequestFullscreen();\n } else if ((this._container as any).webkitRequestFullscreen) {\n (this._container as any).webkitRequestFullscreen();\n } else {\n this._togglePseudoFullScreen();\n }\n }\n\n _togglePseudoFullScreen() {\n this._container.classList.toggle('maplibregl-pseudo-fullscreen');\n this._handleFullscreenChange();\n this._map.resize();\n }\n}\n","import {DOM} from '../../util/dom';\n\nimport type {Map} from '../map';\nimport type {IControl} from './control';\nimport type {TerrainSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * A `TerrainControl` control contains a button for turning the terrain on and off.\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * let map = new Map({TerrainControl: false})\n * .addControl(new TerrainControl({\n * source: \"terrain\"\n * }));\n * ```\n */\nexport class TerrainControl implements IControl {\n options: TerrainSpecification;\n _map: Map;\n _container: HTMLElement;\n _terrainButton: HTMLButtonElement;\n\n /**\n * @param options - the control's options\n */\n constructor(options: TerrainSpecification) {\n this.options = options;\n }\n\n /** {@inheritDoc IControl.onAdd} */\n onAdd(map: Map) {\n this._map = map;\n this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');\n this._terrainButton = DOM.create('button', 'maplibregl-ctrl-terrain', this._container);\n DOM.create('span', 'maplibregl-ctrl-icon', this._terrainButton).setAttribute('aria-hidden', 'true');\n this._terrainButton.type = 'button';\n this._terrainButton.addEventListener('click', this._toggleTerrain);\n\n this._updateTerrainIcon();\n this._map.on('terrain', this._updateTerrainIcon);\n return this._container;\n }\n\n /** {@inheritDoc IControl.onRemove} */\n onRemove() {\n DOM.remove(this._container);\n this._map.off('terrain', this._updateTerrainIcon);\n this._map = undefined;\n }\n\n _toggleTerrain = () => {\n if (this._map.getTerrain()) {\n this._map.setTerrain(null);\n } else {\n this._map.setTerrain(this.options);\n }\n this._updateTerrainIcon();\n };\n\n _updateTerrainIcon = () => {\n this._terrainButton.classList.remove('maplibregl-ctrl-terrain');\n this._terrainButton.classList.remove('maplibregl-ctrl-terrain-enabled');\n if (this._map.terrain) {\n this._terrainButton.classList.add('maplibregl-ctrl-terrain-enabled');\n this._terrainButton.title = this._map._getUIString('TerrainControl.Disable');\n } else {\n this._terrainButton.classList.add('maplibregl-ctrl-terrain');\n this._terrainButton.title = this._map._getUIString('TerrainControl.Enable');\n }\n };\n}\n"],"names":["__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","SuppressedError","pointGeometry","Point","x","y","this","prototype","clone","add","p","_add","sub","_sub","multByPoint","_multByPoint","divByPoint","_divByPoint","mult","k","_mult","div","_div","rotate","a","_rotate","rotateAround","_rotateAround","matMult","m","_matMult","unit","_unit","perp","_perp","round","_round","mag","Math","sqrt","equals","other","dist","distSqr","dx","dy","angle","atan2","angleTo","b","angleWith","angleWithSep","cos","sin","convert","Array","isArray","unitbezier","UnitBezier","p1x","p1y","p2x","p2y","cx","bx","ax","cy","by","ay","sampleCurveX","t","sampleCurveY","sampleCurveDerivativeX","solveCurveX","epsilon","undefined","i","x2","abs","d2","t0","t1","solve","supportsOffscreenCanvas","offscreenCanvasDistorted","offscreenCanvasSupported","OffscreenCanvas","getContext","createImageBitmap","getAABB","points","tlX","Infinity","tlY","brX","brY","min","max","bezier","defaultEasing","clamp","n","wrap","d","w","extend","dest","sources","src","pick","properties","length","id","uniqueId","mapObject","input","iterator","context","output","key","call","filterObject","deepEqual","Object","keys","map","warnOnceHistory","warnOnce","message","console","warn","isCounterClockwise","c","isWorker","self","WorkerGlobalScope","_isSafari","isImageBitmap","image","ImageBitmap","transparentPngUrl","degreesToRadians","degrees","PI","createAbortError","Error","linkEl","reducedMotionQuery","browser","now","performance","bind","Date","frameAsync","abortController","frame","requestAnimationFrame","signal","addEventListener","cancelAnimationFrame","getImageData","img","padding","getImageCanvasContext","width","height","canvas","window","document","createElement","willReadFrequently","drawImage","resolveURL","path","href","hardwareConcurrency","navigator","prefersReducedMotion","matchMedia","matches","DOM","static","props","docStyle","tagName","className","container","el","appendChild","namespaceURI","createElementNS","selectProp","userSelect","style","transformProp","target","type","callback","options","capture","removeEventListener","preventDefault","stopPropagation","suppressClickInternal","setTimeout","element","rect","getBoundingClientRect","offsetWidth","offsetHeight","boundingClientRect","scale","clientX","left","clientLeft","clientY","top","clientTop","getScale","getPoint","touches","push","button","node","parentNode","removeChild","documentElement","testProp","config","MAX_PARALLEL_IMAGE_REQUESTS","MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME","MAX_TILE_CACHE_ZOOM_LEVELS","REGISTERED_PROTOCOLS","WORKER_URL","getProtocol","url","substring","indexOf","GLOBAL_DISPATCHER_ID","AJAXError","constructor","status","statusText","body","super","getReferrer","worker","referrer","location","protocol","parent","makeRequest","requestParameters","test","protocolLoadFn","actor","sendAsync","data","targetMapId","fetch","Request","AbortController","hasOwnProperty","request","method","credentials","headers","cache","has","set","response","ok","blob","parsePromise","arrayBuffer","json","text","aborted","cacheControl","get","expires","makeFetchRequest","mustQueue","xhr","XMLHttpRequest","open","responseType","setRequestHeader","_a","Accept","withCredentials","onerror","onload","JSON","parse","err","getResponseHeader","Blob","abort","send","makeXMLHttpRequest","getJSON","sameOrigin","inComingUrl","urlObj","URL","locationObj","host","webpSupported","supported","testSupport","gl","webpCheckComplete","webpImgTest","webpImgTestOnloadComplete","testWebpTextureUpload","glForTesting","texture","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","isContextLost","deleteTexture","ImageRequest","imageRequestQueue","currentParallelImageRequests","throttleControlCallbackHandleCounter","throttleControlCallbacks","resetRequestQueue","addThrottleControl","handle","removeThrottleControl","callbackHandle","processQueue","getImage","supportImageRefresh","accept","state","onError","error","onSuccess","doImageRequest","itemInQueue","canUseHTMLImageElement","reduce","acc","item","getImagePromise","getImageUsingHtmlImage","HTMLImageElement","byteLength","ImageData","Uint8Array","arrayBufferToImageBitmap","Image","revokeObjectURL","createObjectURL","arrayBufferToImage","maxImageRequests","isThrottled","numImageRequests","topItemInQueue","shift","crossOrigin","fetchPriority","RequestManager","transformRequestFn","_transformRequestFn","transformRequest","setTransformRequest","_addEventListener","listener","listenerList","_removeEventListener","index","splice","Event","ErrorEvent","Evented","on","_listeners","off","_oneTimeListeners","once","fire","event","listens","listeners","slice","oneTimeListeners","_eventedParent","_eventedParentData","setEventedParent","v8Spec","$version","$root","version","required","values","name","metadata","center","zoom","bearing","default","period","units","pitch","light","sky","projection","terrain","sprite","glyphs","transition","layers","source","source_vector","vector","tiles","bounds","scheme","xyz","tms","minzoom","maxzoom","attribution","promoteId","volatile","source_raster","raster","tileSize","source_raster_dem","encoding","terrarium","mapbox","custom","redFactor","blueFactor","greenFactor","baseShift","source_geojson","geojson","buffer","maximum","minimum","filter","tolerance","cluster","clusterRadius","clusterMaxZoom","clusterMinPoints","clusterProperties","lineMetrics","generateId","source_video","video","urls","coordinates","source_image","layer","fill","line","symbol","circle","heatmap","hillshade","background","layout","paint","layout_background","visibility","visible","none","layout_fill","expression","interpolated","parameters","layout_circle","layout_heatmap","layout_line","butt","square","bevel","miter","requires","layout_symbol","point","auto","never","always","cooperative","viewport","both","tokens","right","bottom","horizontal","vertical","uppercase","lowercase","layout_raster","layout_hillshade","filter_operator","in","all","any","geometry_type","LineString","Polygon","function","stops","base","property","identity","exponential","interval","categorical","colorSpace","rgb","lab","hcl","function_stop","anchor","position","color","intensity","exaggeration","mercator","globe","paint_fill","paint_line","paint_circle","paint_heatmap","paint_symbol","overridable","paint_raster","linear","nearest","paint_hillshade","paint_background","duration","delay","constant","refProperties","deref","forEach","derefLayers","create","ref","addCommand","commands","command","addSource","sourceId","after","args","removeSource","sourcesRemoved","updateSource","canUpdateGeoJSON","before","prop","diffLayerPropertyChanges","layerId","klass","pluckId","indexById","group","ValidationError","identifier","__line__","extendBy","inputs","ExpressionParsingError","Scope","bindings","concat","NullType","kind","NumberType","StringType","BooleanType","ColorType","ObjectType","ValueType","CollatorType","FormattedType","PaddingType","ResolvedImageType","VariableAnchorOffsetCollectionType","array$1","itemType","N","toString$1","valueMemberTypes","checkSubtype","expected","memberType","isValidType","provided","allowedTypes","some","isValidNativeType","verifyType","sample","Xn","Zn","t2","t3","deg2rad","rad2deg","constrainAngle","rgbToLab","r","g","alpha","z","xyz2lab","rgb2xyz","l","pow","labToRgb","isNaN","lab2xyz","xyz2rgb","parseHex","hex","parseInt","padEnd","parseAlpha","asPercentage","validateNumbers","array","Number","namedColors","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","Color","premultiplied","overwriteGetter","rgba","toLowerCase","trim","namedColorsMatch","startsWith","rgbMatch","match","_","rp","f1","gp","f2","bp","f3","ap","argFormat","join","valFormat","maxValue","hslMatch","h","s","hsla","f","hslToRgb","parseCssColor","rgbColor","NaN","rgbToHcl","getterKey","lazyValue","defineProperty","toString","transparent","Collator","caseSensitive","diacriticSensitive","locale","sensitivity","collator","Intl","usage","compare","lhs","rhs","resolvedLocale","resolvedOptions","FormattedSection","fontStack","textColor","Formatted","sections","unformatted","isEmpty","section","fromString","Padding","val","stringify","anchors","Set","VariableAnchorOffsetCollection","anchorValue","offsetValue","ResolvedImage","available","validateRGBA","isValue","mixed","typeOf","String","Literal","expectedType","evaluate","eachChild","outputDefined","RuntimeError","toJSON","types$1","string","number","boolean","object","Assertion","floor","parsed","ctx","fn","every","arg","types","Coercion","Boolean","parseColor","pad","coll","num","geometryTypes","EvaluationContext","globals","feature","featureState","formattedSection","_parseColorCache","availableImages","canonical","geometryType","geometry","canonicalID","cached","ParsingContext","registry","isConstantFunc","scope","errors","part","_isConstant","expr","_parse","annotate","typeAnnotation","op","Expr","actual","ec","Let","binding","Var","boundExpression","At","In","needle","haystack","IndexOf","fromIndex","rawIndex","Match","inputType","outputType","cases","outputs","otherwise","labels","labelContext","label","MAX_SAFE_INTEGER","out","Case","branches","Slice","beginIndex","endIndex","findStopLessThanOrEqualTo","lastIndex","currentValue","nextValue","lowerIndex","upperIndex","currentIndex","Step","labelKey","valueKey","stopCount","getDefaultExportFromCjs","__esModule","UnitBezier$1","from","to","interpolate","spaceKey","hue0","chroma0","light0","alphaF","hue1","chroma1","light1","alphaT","hue","chroma","dh","hclToRgb","variableAnchorOffsetCollection","fromValues","toValues","fx","fy","tx","ty","Interpolate","operator","interpolation","lower","upper","exponentialInterpolation","controlPoints","rest","interpolationFactor","outputLower","outputUpper","lowerValue","upperValue","difference","progress","Coalesce","parsedArgs","needsAnnotation","requestedImageName","argCount","isComparableType","eqCollate","makeComparison","compareBasic","compareWithCollator","isOrderComparison","Comparison","hasUntypedArgument","lt","rt","Equals","NotEquals","LessThan","GreaterThan","LessThanOrEqual","GreaterThanOrEqual","CollatorExpression","NumberFormat","currency","minFractionDigits","maxFractionDigits","minimumFractionDigits","maximumFractionDigits","format","FormatExpression","firstArg","nextTokenMayBeObject","font","lastExpression","content","evaluatedContent","ImageExpression","evaluatedImageName","Length","EXTENT","getTileCoordinates","log","tilesAtZoom","getLngLatFromTileCoord","coord","mercatorX","mercatorY","atan","exp","updateBBox","bbox","boxWithinBox","bbox1","bbox2","pointOnBoundary","p1","p2","x1","y1","y2","segmentIntersectSegment","v1","v2","twoSided","lineIntersectPolygon","polygon","ring","j","pointWithinPolygon","rings","trueIfOnBoundary","inside","pointWithinPolygons","polygons","lineStringWithinPolygon","lineStringWithinPolygons","q1","q2","x3","y3","det1","det2","getTilePolygon","getTilePolygons","updatePoint","polyBBox","worldSize","halfWorldSize","getTilePoints","pointBBox","shifts","tilePoints","getTileLines","lineBBox","tileLines","tileLine","Within","geometries","polygonsCoords","features","polygonGeometry","tilePolygon","tilePolygons","pointsWithinPolygons","linesWithinPolygons","TinyQueue","_down","_up","pop","peek","pos","current","halfLength","bestChild","quickselect","arr","quickselectStep","defaultCompare","sd","swap","tmp","classifyRings","maxRings","ccw","area","calculateSignedArea","compareAreas","sum","len","FE","E2","RAD","CheapRuler","lat","coslat","w2","kx","ky","distance","pointOnLine","minX","minY","minI","minT","minDist","sqDist","deg","compareDistPair","getRangeSize","range","isRangeSafe","threshold","splitRange","isLine","size","size1","getBBox","coords","getPolygonBBox","isValidBBox","bboxToBBoxDistance","ruler","pointToLineDistance","nearestPoint","segmentToSegmentDistance","dist1","dist2","lineToLineDistance","line1","range1","line2","range2","pointsToPointsDistance","points1","points2","pointToPolygonDistance","front","back","lineToPolygonDistance","polygonIntersect","poly1","poly2","polygonToPolygonDistance","polygon1","polygon2","currentMiniDist","ring1","len1","ring2","len2","updateQueue","distQueue","miniDist","rangeA","tempDist","updateQueueTwoSets","pointSet1","pointSet2","pointsToPolygonDistance","distPair","newRangesA","pointSetToPointSetDistance","isLine1","isLine2","rangeB","threshold1","threshold2","sublibe","newRangesB","toSimpleGeometry","lineString","Distance","flat","pointPosition","pointToGeometryDistance","linePositions","lineStringToGeometryDistance","polygonToGeometryDistance","expressions$1","at","case","coalesce","let","literal","var","within","CompoundExpression","_evaluate","definition","definitions","availableOverloads","overloads","signature","signatureContext","params","isExpressionConstant","argParseFailed","signatures","stringifySignature","actualTypes","obj","v","varargs","isTypeAnnotation","childrenConstant","child","isFeatureConstant","isGlobalPropertyConstant","isStateConstant","success","supportsPropertyExpression","spec","supportsZoomExpression","supportsInterpolation","getType","isFunction$1","identityFunction","createFunction","propertySpec","isColor","zoomAndFeatureDependent","zoomDependent","parseFn","stop","innerFun","hashedStops","categoricalKeyType","evaluateExponentialFunction","evaluateIntervalFunction","evaluateCategoricalFunction","evaluateIdentityFunction","featureFunctions","zoomStops","featureFunctionStops","interpolationType","coalesce$1","keyType","interp","evaluatedLower","evaluatedUpper","register","typeof","heatmapDensity","lineProgress","accumulated","ln2","LN2","pi","E","log10","LN10","ln","log2","asin","acos","ceil","binarySearch","isSupportedScript","upcase","toUpperCase","downcase","StyleExpression","_warningHistory","_evaluator","_defaultValue","_enumValues","evaluateWithoutErrorHandling","isExpression","createExpression","parser","enum","formatted","resolvedImage","getExpectedType","ZoomConstantExpression","_styleExpression","isStateDependent","ZoomDependentExpression","createPropertyExpression","expressionInput","isFeatureConstantResult","isZoomConstant","zoomCurve","findZoomCurve","StylePropertyFunction","specification","_parameters","_specification","serialized","childResult","isExpressionFilter","filterSpec","createFilter","needGeometry","convertFilter$1","compiled","globalProperties","geometryNeeded","convertComparisonOp$1","convertNegation","filters","convertInOp$1","convertHasOp$1","sort","validateConstants","constants","unbundle","valueOf","deepUnbundle","unbundledValue","validateObject","elementSpecs","valueSpec","elementValidators","objectElementValidators","styleSpec","validateSpec","objectKey","elementSpecKey","split","elementSpec","validateElement","validateArray","arraySpec","validateArrayElement","arrayElementValidator","arrayElementSpec","arrayIndex","validateNumber","validateFunction","functionValueSpec","functionType","stopKeyType","previousStopDomainValue","previousStopDomainZoom","stopDomainValues","isZoomFunction","isPropertyFunction","isZoomAndPropertyFunction","validateFunctionStop","validateStopDomainValue","reportValue","isFinite","validateExpression","expressionContext","expressionObj","propertyKey","propertyType","validateEnum","validateFilter","validateNonExpressionFilter","validateProperty","layerSpec","layerType","transitionMatch","tokenMatch","exec","validatePaintProperty","validateLayoutProperty","validateLayer","otherLayer","sourceType","validateString","validateSource","replace","sourceName","rasterDEM","rasterDEMSpec","rootType","isCustomEncoding","customEncodingKeys","encodingName","includes","validateRasterDEMSource","mapExpr","reduceExpr","validateLight","lightSpec","validateSky","skySpec","validateTerrain","terrainSpec","validateSprite","allSpriteIds","allSpriteURLs","VALIDATORS","projectionSpec","validate","validateGlyphsUrl","validateStyleMin","sortErrors","injectValidateSpec","validator","wrapCleanErrors","inner","paintProperty","layoutProperty","validateStyle","emitValidationErrors","emitter","hasErrors","TransferableGridIndex","extent","cells","ArrayBuffer","Int32Array","start","end","subarray","bboxesOffset","bboxes","insert","_insertReadonly","uid","_forEachCell","_insertCell","cellIndex","query","intersectionTest","_queryCell","seenUids","cell","u","offset","arg1","arg2","cx1","_convertToCellCoord","cy1","cx2","cy2","_convertFromCellCoord","toArrayBuffer","metadataLength","totalCellLength","grid","transferables","writeable","omit","shallow","expressions","_classRegistryKey","isArrayBuffer","getClassRegistryKey","$name","isSerializeHandledByBuiltin","classRegistryKey","isRegistered","RegExp","isView","serialize","deserialize","ZoomHistory","first","update","floorZ","lastIntegerZoom","lastIntegerZoomTime","lastZoom","lastFloorZoom","unicodeBlockLookup","char","Khmer","Katakana","Kanbun","allowsVerticalWritingMode","chars","charHasUprightVerticalOrientation","charCodeAt","sanitizedRegExpFromScriptCodes","scriptCodes","supportedPropertyEscapes","code","pe","ideographicBreakingRegExp","isChar","fromCodePoint","rtlScriptRegExp","charInRTLScript","charInSupportedScript","canRenderRTL","stringContainsRTLText","rtlWorkerPlugin","applyArabicShaping","processBidirectionalText","processStyledBidirectionalText","pluginStatus","pluginURL","setState","getState","setMethods","rtlTextPlugin","isParsed","getPluginURL","getRTLTextPluginStatus","EvaluationParameters","fadeDuration","zoomHistory","str","isStringInSupportedScript","crossFadingFactor","getCrossfadeParameters","fraction","fromScale","toScale","PropertyValue","normalizePropertyExpression","isDataDriven","possiblyEvaluate","TransitionablePropertyValue","transitioned","prior","TransitioningPropertyValue","untransitioned","Transitionable","_properties","_values","defaultTransitionablePropertyValues","getValue","setValue","getTransition","setTransition","Transitioning","begin","finalValue","easeCubicInOut","defaultTransitioningPropertyValues","PossiblyEvaluated","hasTransition","Layout","defaultPropertyValues","hasValue","PossiblyEvaluatedPropertyValue","isConstant","constantOr","defaultPossiblyEvaluatedValues","DataConstantProperty","interpolationFn","interpolates","DataDrivenProperty","overrides","interpolatedValue","CrossFadedDataDrivenProperty","evaluatedValue","constantValue","_calculate","cameraVal","mid","CrossFadedProperty","ColorRampProperty","Properties","overridableProperties","defaultPropertyValue","defaultTransitionablePropertyValue","TRANSITION_SUFFIX","StyleLayer","_featureFilter","sourceLayer","_unevaluatedLayout","_transitionablePaint","setPaintProperty","setLayoutProperty","_transitioningPaint","_crossfadeParameters","getLayoutProperty","_validate","getPaintProperty","endsWith","transitionable","isCrossFadedProperty","wasDataDriven","oldValue","_handleSpecialPaintPropertyUpdate","newValue","_handleOverridablePaintPropertyUpdate","isHidden","updateTransitions","recalculate","is3D","isTileClipped","hasOffscreenPass","resize","viewTypes","Int8","Int8Array","Uint8","Int16","Int16Array","Uint16","Uint16Array","Int32","Uint32","Uint32Array","Float32","Float32Array","Struct","structArray","_structArray","_pos1","_pos2","_pos4","_pos8","StructArray","isTransferred","capacity","_trim","bytesPerElement","_refreshViews","clear","reserve","oldUint8Array","uint8","createLayout","members","alignment","maxSize","member","typeSize","BYTES_PER_ELEMENT","memberOffset","align","components","StructArrayLayout2i4","int16","emplaceBack","v0","emplace","o2","StructArrayLayout3i6","StructArrayLayout4i8","v3","StructArrayLayout2i4i12","v4","v5","StructArrayLayout2i4ub8","o1","StructArrayLayout2f8","float32","o4","StructArrayLayout10ui20","uint16","v6","v7","v8","v9","StructArrayLayout4i4ui4i24","v10","v11","StructArrayLayout3f12","StructArrayLayout1ul4","uint32","StructArrayLayout6i1ul2ui20","StructArrayLayout2i2i2i12","StructArrayLayout2f1f2i16","StructArrayLayout2ub2f2i16","StructArrayLayout3ui6","StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48","v12","v13","v14","v15","v16","StructArrayLayout8i15ui1ul2f2ui64","v17","v18","v19","v20","v21","v22","v23","v24","v25","v26","v27","StructArrayLayout1f4","StructArrayLayout1ui2f12","StructArrayLayout1ul2ui8","StructArrayLayout2ui4","StructArrayLayout1ui2","StructArrayLayout4f16","CollisionBoxStruct","anchorPointX","anchorPointY","featureIndex","sourceLayerIndex","bucketIndex","anchorPoint","CollisionBoxArray","PlacedSymbolStruct","anchorX","anchorY","glyphStartIndex","numGlyphs","vertexStartIndex","lineStartIndex","lineLength","segment","lowerSize","upperSize","lineOffsetX","lineOffsetY","writingMode","placedOrientation","hidden","crossTileID","associatedIconIndex","PlacedSymbolArray","SymbolInstanceStruct","rightJustifiedTextSymbolIndex","centerJustifiedTextSymbolIndex","leftJustifiedTextSymbolIndex","verticalPlacedTextSymbolIndex","placedIconSymbolIndex","verticalPlacedIconSymbolIndex","textBoxStartIndex","textBoxEndIndex","verticalTextBoxStartIndex","verticalTextBoxEndIndex","iconBoxStartIndex","iconBoxEndIndex","verticalIconBoxStartIndex","verticalIconBoxEndIndex","numHorizontalGlyphVertices","numVerticalGlyphVertices","numIconVertices","numVerticalIconVertices","useRuntimeCollisionCircles","textBoxScale","collisionCircleDiameter","textAnchorOffsetStartIndex","textAnchorOffsetEndIndex","SymbolInstanceArray","GlyphOffsetArray","getoffsetX","SymbolLineVertexArray","getx","gety","gettileUnitDistanceFromAnchor","TextAnchorOffsetStruct","textAnchor","textOffset0","textOffset1","TextAnchorOffsetArray","FeatureIndexStruct","FeatureIndexArray","PosArray","Pos3dArray","RasterBoundsArray","CircleLayoutArray","FillLayoutArray","FillExtrusionLayoutArray","LineLayoutArray","LineExtLayoutArray","PatternLayoutArray","SymbolLayoutArray","SymbolDynamicLayoutArray","SymbolOpacityArray","CollisionBoxLayoutArray","CollisionCircleLayoutArray","CollisionVertexArray","QuadTriangleArray","TriangleIndexArray","LineIndexArray","LineStripIndexArray","SegmentVector","segments","prepareSegment","numVertices","layoutVertexArray","indexArray","sortKey","MAX_VERTEX_ARRAY_LENGTH","vertexLength","vertexOffset","primitiveOffset","primitiveLength","destroy","vaos","packUint8ToFloat","patternAttributes","module","seed","remainder","bytes","h1","h1b","c1","c2","k1","murmur3","require$$0","murmur2","murmurhashJsModule","exports","FeaturePositionMap","ids","positions","indexed","getNumericId","getPositions","intId","Float64Array","numValue","pivot","Uniform","Uniform1i","uniform1i","Uniform1f","uniform1f","Uniform2f","uniform2f","Uniform3f","uniform3f","Uniform4f","uniform4f","UniformColor","emptyMat4","UniformMatrix4f","uniformMatrix4fv","packColor","ConstantBinder","names","uniformNames","setUniform","uniform","getBinding","CrossFadedConstantBinder","patternFrom","patternTo","pixelRatioFrom","pixelRatioTo","setConstantPatternPositions","posTo","posFrom","pixelRatio","tlbr","uniformName","substr","SourceExpressionBinder","PaintVertexArray","paintVertexAttributes","paintVertexArray","populatePaintArray","newLength","imagePositions","_setPaintValue","updatePaintArray","upload","paintVertexBuffer","updateData","createVertexBuffer","CompositeExpressionBinder","useIntegerZoom","minColor","maxColor","currentZoom","factor","CrossFadedCompositeBinder","zoomInPaintVertexArray","zoomOutPaintVertexArray","_setPaintValues","patterns","imageMin","imageMid","imageMax","tl","br","zoomInPaintVertexBuffer","zoomOutPaintVertexBuffer","ProgramConfiguration","filterProperties","binders","_buffers","paintAttributeNames","propType","isCrossFaded","StructArrayLayout","layoutType","cacheKey","getMaxValue","binder","populatePaintArrays","updatePaintArrays","featureStates","featureMap","vtLayer","dirty","defines","getBinderAttributes","getBinderUniforms","uniforms","getPaintVertexBuffers","getUniforms","locations","setUniforms","binderUniforms","updatePaintBuffers","crossfade","patternVertexBuffer","ProgramConfigurationSet","programConfigurations","needsUpload","_featureMap","_bufferOffset","binderType","defaultLayouts","composite","layoutException","getLayoutException","MAX","BITS","MIN","loadGeometry","toEvaluationFeature","addCircleVertex","extrudeX","extrudeY","CircleBucket","overscaling","layerIds","hasPattern","stateDependentLayerIds","populate","styleLayer","bucketFeatures","circleSortKey","sortFeaturesByKey","evaluationFeature","bucketFeature","addFeature","states","stateDependentLayers","uploadPending","uploaded","layoutVertexBuffer","layoutAttributes","indexBuffer","createIndexBuffer","polygonIntersectsPolygon","polygonA","polygonB","polygonContainsPoint","lineIntersectsLine","polygonIntersectsBufferedPoint","radius","pointIntersectsBufferedLine","polygonIntersectsMultiPolygon","multiPolygon","multiPolygonContainsPoint","lineIntersectsBufferedLine","lineA","lineB","a0","a1","lineSegmentIntersectsLineSegment","b0","b1","radiusSquared","distToSegmentSquared","l2","edgeIntersectsBox","e1","e2","corners","dir","getMaximumPaintValue","bucket","translateDistance","translate","queryGeometry","translateAnchor","pixelsToTileUnits","pt","translated","properties$9","EPSILON","ARRAY_TYPE","glMatrix.ARRAY_TYPE","invert","a00","a01","a02","a03","a10","a11","a12","a13","a20","a21","a22","a23","a30","a31","a32","a33","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","det","multiply","b2","b3","rotateX","rad","rotateZ","hypot","arguments","perspective","fovy","aspect","near","far","nf","ortho","lr","bt","mul","transformMat4","sqrLen","CircleStyleLayer","createBucket","queryRadius","circleBucket","queryIntersectsFeature","transform","pixelPosMatrix","translatedPolygon","alignWithMap","transformedPolygon","projectPoint","projectQueryGeometry","transformedSize","transformedPoint","adjustedSize","projectedCenter","vec4.transformMat4","cameraToCenterDistance","HeatmapBucket","properties$8","createImage","channels","Uint8ClampedArray","RangeError","resizeImage","newImage","copyImage","srcImg","dstImg","srcPt","dstPt","srcData","dstData","srcOffset","dstOffset","AlphaImage","RGBAImage","copy","renderColorRamp","evaluationGlobals","resolution","clips","renderPixel","stride","evaluationKey","pxColor","clip","HEATMAP_FULL_RENDER_FBO_KEY","HeatmapStyleLayer","heatmapFbos","Map","_updateColorRamp","colorRamp","colorRampTexture","delete","properties$7","HillshadeStyleLayer","earcut","holeIndices","dim","hasHoles","outerLen","outerNode","linkedList","triangles","prev","invSize","queue","list","steiner","getLeftmost","compareX","eliminateHole","eliminateHoles","maxX","maxY","earcutLinked","clockwise","last","signedArea","insertNode","removeNode","filterPoints","again","ear","pass","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","x0","y0","pointInTriangle","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","hole","bridge","hx","hy","qx","mx","my","tanMin","sectorContainsSector","findHoleBridge","bridgeReverse","leftmost","px","py","intersectsPolygon","middleInside","sign","o3","onSegment","a2","createNode","an","patternDependencies","patternProperty","constantPattern","addPatternDependencies","patternFeature","patternPropertyValue","FillBucket","patternFeatures","indexArray2","segments2","fillSortKey","addFeatures","indexBuffer2","triangleSegment","triangleIndex","flattened","lineSegment","lineIndex","indices","properties$6","FillStyleLayer","outlineColor","centroidAttributes","vectortilefeature","VectorTileFeature","pbf","_pbf","_geometry","_keys","readFields","readFeature","tag","readVarint","readTag","cmd","lines","cmdLen","readSVarint","toGeoJSON","project","vectortilelayer","VectorTileLayer","_features","readLayer","readString","readFloat","readDouble","readVarint64","readBoolean","readValueMessage","readTile","vectorTile","VectorTile","require$$1","require$$2","vectorTileFeatureTypes","mvt","FACTOR","addVertex","vertexArray","nx","ny","nz","FillExtrusionBucket","centroidVertexArray","centroidVertexBuffer","centroid","vertexCount","isEntirelyOutside","edgeDistance","isBoundaryEdge","bottomRight","averageX","averageY","properties$5","FillExtrusionStyleLayer","projectedQueryGeometry","projected","zBase","zTop","projectedBase","projectedTop","baseXZ","baseYZ","baseZZ","baseWZ","topXZ","topYZ","topZZ","topWZ","ringBase","ringTop","sX","sY","sZ","sW","baseZ","baseW","topX","topY","topZ","topW","projectExtrusion","closestDistance","getIntersectionDistance","topA","face","checkIntersection","dot","projectedFace","ab","ac","dotABAB","dotABAC","dotACAC","dotAPAB","dotAPAC","denom","lineLayoutAttributes","lineLayoutAttributesExt","COS_HALF_SHARP_CORNER","MAX_LINE_DISTANCE","LINE_DISTANCE_BUFFER_BITS","LineBucket","lineClipsArray","gradients","layoutVertexArray2","maxLineLength","lineSortKey","patternBucketFeature","layoutVertexBuffer2","layoutAttributesExt","lineFeatureClips","cap","miterLimit","roundLimit","lineClips","addLine","vertices","scaledDistance","totalDistance","updateScaledDistance","isPolygon","sharpCornerOffset","currentVertex","prevVertex","nextVertex","prevNormal","nextNormal","joinNormal","cosAngle","cosHalfAngle","miterLength","approxAngle","isSharpCorner","lineTurnsLeft","prevSegmentLength","newPrevVertex","updateDistance","addCurrentVertex","middleVertex","currentJoin","bevelLength","offsetA","offsetB","extrude","addHalfVertex","nextSegmentLength","newCurrentVertex","normal","endLeft","endRight","rightX","rightY","up","linesofarScaled","properties$4","LineFloorwidthProperty","lineFloorwidthProperty","LineStyleLayer","gradientVersion","gradientExpression","stepInterpolant","isZoomExpression","lineBucket","getLineWidth","halfWidth","lineOffset","newRings","ringIndex","newRing","aToB","bToC","offsetLine","multiLine","polygonIntersectsBufferedMultiLine","lineWidth","lineGapWidth","symbolLayoutAttributes","dynamicLayoutAttributes","collisionVertexAttributes","collisionBoxLayout","collisionCircleLayout","transformText","toLocaleUpperCase","toLocaleLowerCase","transformTextInternal","verticalizedCharacterMap","$","Pbf","ieee754","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","buf","Varint","Fixed64","Bytes","Fixed32","SHIFT_LEFT_32","SHIFT_RIGHT_32","utf8TextDecoder","TextDecoder","readPackedEnd","toNum","low","high","isSigned","makeRoomForExtraLength","startPos","extraLen","realloc","writePackedVarint","writeVarint","writePackedSVarint","writeSVarint","writePackedFloat","writeFloat","writePackedDouble","writeDouble","writePackedBoolean","writeBoolean","writePackedFixed32","writeFixed32","writePackedSFixed32","writeSFixed32","writePackedFixed64","writeFixed64","writePackedSFixed64","writeSFixed64","readUInt32","writeInt32","readInt32","readField","skip","readMessage","readFixed32","readSFixed32","readFixed64","readSFixed64","readVarintRemainder","decode","readUtf8TextDecoder","bytesPerSequence","fromCharCode","readUtf8","readBytes","readPackedVarint","readPackedSVarint","readPackedBoolean","readPackedFloat","readPackedDouble","readPackedFixed32","readPackedSFixed32","readPackedFixed64","readPackedSFixed64","writeTag","finish","writeBigVarintLow","lsb","writeBigVarintHigh","writeBigVarint","writeString","lead","writeUtf8","writeBytes","writeRawMessage","writeMessage","writeBytesField","writeFixed32Field","writeSFixed32Field","writeFixed64Field","writeSFixed64Field","writeVarintField","writeSVarintField","writeStringField","writeFloatField","writeDoubleField","writeBooleanField","border","readFontstacks","readFontstack","bitmap","advance","readGlyph","metrics","glyph","potpack","boxes","maxWidth","box","spaces","space","ImagePosition","paddedRect","stretchX","stretchY","textFitWidth","textFitHeight","displaySize","IMAGE_PADDING","WritingMode","getAnchorAlignment","horizontalAlign","verticalAlign","icons","iconPositions","patternPositions","haveRenderCallbacks","bins","addImages","bin","images","hasRenderCallback","patchUpdatedImages","imageManager","dispatchRenderCallbacks","updatedImages","patchUpdatedImage","SIZE_PACK_FACTOR","MAX_PACKED_SIZE","getSizeData","tileZoom","layoutSize","minZoom","maxZoom","minSize","evaluateSizeForFeature","sizeData","uSize","uSizeT","evaluateSizeForZoom","getOverlapMode","overlapProp","allowOverlapProp","overlap","shaderOpacityAttributes","ox","oy","sizeVertex","isSDF","pixelOffsetX","pixelOffsetY","minFontScaleX","minFontScaleY","aSizeX","aSizeY","addDynamicAttributes","dynamicLayoutVertexArray","containsRTLText","formattedText","SymbolBuffers","opacityVertexArray","hasVisibleVertices","placedSymbolArray","dynamicIndexBuffer","dynamicLayoutVertexBuffer","opacityVertexBuffer","itemSize","CollisionBuffers","LayoutArray","IndexArray","collisionVertexArray","collisionVertexBuffer","SymbolBucket","collisionBoxArray","hasRTLText","sortKeyRanges","collisionCircleArray","placementInvProjMatrix","mat4.identity","placementViewportMatrix","unevaluatedLayoutValues","textSizeData","iconSizeData","canOverlap","sortFeaturesByY","writingModes","wm","sourceID","createArrays","icon","glyphOffsetArray","lineVertexArray","symbolInstances","textAnchorOffsets","calculateGlyphDependencies","stack","textAlongLine","allowVerticalPlacement","doesAllowVerticalWritingMode","verticalChar","charAt","textFont","textField","iconImage","hasText","hasIcon","symbolSortKey","iconDependencies","stacks","glyphDependencies","resolvedTokens","getValueAndResolveTokens","factory","bucketHasRTLText","sectionFont","sectionStack","leftIndex","rightIndex","mergedFeatures","mergedIndex","mergeFromRight","leftKey","rightKey","geom","mergeFromLeft","getKey","onRight","mergeLines","hasDebugData","textCollisionBox","iconCollisionBox","destroyDebugData","addToLineVertexArray","sumForwardLength","sumBackwardLength","tileUnitDistanceFromAnchor","vertex","addSymbols","arrays","quads","alongLine","labelAnchor","glyphOffsetArrayStart","tr","bl","tex","pixelOffsetTL","pixelOffsetBR","glyphOffset","sectionIndex","_addCollisionDebugVertex","addCollisionDebugVertices","boxAnchorPoint","symbolInstance","addDebugCollisionBoxes","startIndex","isText","generateCollisionDebugBuffers","_deserializeCollisionBoxesForSymbol","textStartIndex","textEndIndex","verticalTextStartIndex","verticalTextEndIndex","iconStartIndex","iconEndIndex","verticalIconStartIndex","verticalIconEndIndex","collisionArrays","textBox","textFeatureIndex","verticalTextBox","verticalTextFeatureIndex","iconBox","iconFeatureIndex","verticalIconBox","verticalIconFeatureIndex","deserializeCollisionBoxes","hasTextData","hasIconData","hasTextCollisionBoxData","hasIconCollisionBoxData","addIndicesForPlacedSymbol","iconOrText","placedSymbolIndex","placedSymbol","vertexIndex","getSortedSymbolIndexes","sortedAngle","symbolInstanceIndexes","rotatedYs","featureIndexes","aIndex","bIndex","addToSortKeyRanges","symbolInstanceIndex","symbolInstanceEnd","symbolInstanceStart","sortFeatures","featureSortOrder","MAX_GLYPHS","properties$3","runtimeType","getOverride","o","hasOverride","FormatSectionOverride","defaultValue","SymbolStyleLayer","deduped","_setPaintOverrides","unevaluated","resolveTokens","hasPaintOverride","overridden","override","styleExpression","propertyName","hasOverrides","checkSections","checkExpression","properties$2","BackgroundStyleLayer","properties$1","RasterStyleLayer","CustomStyleLayer","implementation","onAdd","painter","onRemove","renderingMode","prerender","createStyleLayer","coerceSpriteToArray","resultArray","dedupArray","normalizeSpriteURL","extension","Texture","useMipmap","pixelStoreUnpackFlipY","pixelStoreUnpack","pixelStoreUnpackPremultiplyAlpha","premultiply","HTMLCanvasElement","HTMLVideoElement","texSubImage2D","isSizePowerOfTwo","generateMipmap","minFilter","LINEAR_MIPMAP_NEAREST","LINEAR","texParameteri","TEXTURE_MAG_FILTER","TEXTURE_MIN_FILTER","TEXTURE_WRAP_S","TEXTURE_WRAP_T","renderStyleImage","userImage","render","ImageManager","callbackDispatchedThisFrame","loaded","requestors","atlasImage","isLoaded","setLoaded","promiseResolve","_getImagesForIds","spriteData","addImage","valid","_validateStretch","_validateContent","stretch","updateImage","oldImage","removeImage","listImages","getImages","_reject","hasAllDependencies","sdf","getPixelSize","getPattern","pattern","_updatePatternAtlas","atlasTexture","CLAMP_TO_EDGE","dst","beginFrame","INF","edt","gridSize","edt1d","qr","GlyphManager","requestManager","localIdeographFontFamily","entries","setURL","getGlyphs","glyphsPromises","_getAndCacheGlyphsPromise","updatedGlyphs","entry","requests","ranges","_tinySDF","promise","loadGlyphRange","_doesCharSupportLocalGlyph","fontFamily","tinySDF","fontWeight","TinySDF","fontSize","cutoff","draw","glyphWidth","glyphHeight","glyphLeft","glyphTop","glyphAdvance","isDoubleResolution","fontstack","urlTemplate","Protobuf","fontStyle","_createCanvas","textBaseline","textAlign","fillStyle","gridOuter","gridInner","actualBoundingBoxAscent","actualBoundingBoxDescent","actualBoundingBoxLeft","actualBoundingBoxRight","measureText","clearRect","fillText","imgData","LightPositionProperty","azimuthal","polar","sphericalToCartesian","lightProperties","Light","lightOptions","_transitionable","setLight","_transitioning","getLight","Sky","setSky","getSky","calculateFogBlendOpacity","LineAtlas","nextRow","dashEntry","getDash","dasharray","addDash","getDashRanges","lineAtlasWidth","isDash","zeroLength","currentDashLength","dashLength","addRoundDash","halfStretch","currIndex","distLeft","distRight","signedDistance","distMiddle","distEdge","addRegularDash","ALPHA","REPEAT","ThrottledInvoker","methodToThrottle","_methodToThrottle","_triggered","MessageChannel","_channel","port2","onmessage","trigger","port1","postMessage","remove","Actor","mapId","resolveRejects","tasks","taskQueue","abortControllers","messageHandlers","invoker","process","subscription","unsubscribe","subscribe","receive","globalScope","registerMessageHandler","handler","random","cancelMessage","origin","sourceMapId","buffers","messageToPost","assign","transfer","processTask","task","resolveReject","completeTask","responseMessage","PRELOAD_POOL_ID","WorkerPool","active","acquire","workers","workerCount","Worker","release","numActive","terminate","isPreloaded","availableLogicalProcessors","globalWorkerPool","globalDispatcher","getGlobalWorkerPool","userAgent","safari","isSafari","globalThis","Dispatcher","workerPool","actors","currentActor","broadcast","promises","getActor","mapRemoved","getGlobalDispatcher","_mapId","getPixelPosMatrix","tileID","mat4.create","mat4.translate","mat4.scale","mat4.multiply","calculatePosMatrix","toUnwrapped","queryRenderedFeatures","sourceCache","styleLayers","serializedLayers","has3DLayer","layerID","queryIncludes3DLayer","maxPitchScaleFactor","tilesIn","sortTilesIn","renderedFeatureLayers","tileIn","wrappedTileID","wrapped","queryResults","tile","_state","cameraQueryGeometry","wrappedIDLayerMap","wrappedID","wrappedIDLayers","tileFeatures","wrappedIDFeatures","resultFeatures","tileFeature","mergeRenderedFeatureLayers","featureWrapper","getFeatureState","idA","idB","overscaledZ","loadTileJson","tileJSON","vector_layers","vectorLayerIds","earthRadius","LngLat","lng","toArray","distanceTo","lngLat","lat1","lat2","lon","LngLatBounds","sw","ne","setSouthWest","setNorthEast","_ne","_sw","sw2","ne2","getCenter","getSouthWest","getNorthEast","getNorthWest","getWest","getNorth","getSouthEast","getEast","getSouth","contains","lnglat","containsLongitude","latAccuracy","lngAccuracy","adjustAntiMeridian","earthCircumference","circumferenceAtLatitude","latitude","mercatorXfromLng","mercatorYfromLat","mercatorZfromAltitude","altitude","latFromMercatorY","MercatorCoordinate","lngLatLike","toLngLat","toAltitude","meterInMercatorCoordinateUnits","TileBounds","validateBounds","level","VectorTileSource","dispatcher","eventedParent","reparseOverscaled","_loaded","_options","_collectResourceTiming","collectResourceTiming","load","dataType","_tileJSONRequest","_requestManager","sourceCaches","clearTiles","tileBounds","sourceDataType","hasTile","setSourceProperty","setTiles","setUrl","loadTile","getPixelRatio","overscaleFactor","showCollisionBoxes","messageType","reloadPromise","_afterTileLoadWorkerResponse","resourceTiming","_refreshExpiredTiles","setExpiryData","loadVectorData","catch","abortTile","unloadTile","unloadVectorData","RasterTileSource","roundZoom","getTileTexture","saveTileTexture","getMercCoords","CanonicalTileID","isInBoundsForTileZoomXY","calculateKey","quadkey","mask","getQuadkey","isChildOf","dz","getTilePoint","UnwrappedTileID","OverscaledTileID","scaledTo","targetZ","zDifference","calculateScaledKey","withWrap","children","sourceMaxZoom","isLessThan","unwrapTo","_idx","MIN_SAFE_INTEGER","ele","pixels","unpack","getUnpackVector","getPixels","backfillBorder","borderTile","xMin","xMax","yMin","yMax","RasterDEMTileSource","neighboringTiles","_getNeighboringTiles","rawImageData","readImageNow","dem","needsHillshadePrepare","needsTerrainPrepare","VideoFrame","fillRect","isOffscreenCanvasDistorted","timestamp","swapBR","copyTo","destRowOffset","sourceLeft","sourceTop","computeVideoFrameParameters","close","readImageUsingVideoFrame","pxw","nxw","backfilled","demTexture","fbo","GeoJSONSource","_removed","_pendingLoads","_data","workerOptions","geojsonVtOptions","superclusterOptions","minPoints","_updateWorkerData","setData","diff","getData","setClusterOptions","getClusterExpansionZoom","clusterId","getClusterChildren","getClusterLeaves","limit","dataDiff","abandoned","rasterBoundsAttributes","ImageSource","newCoordinates","_request","_finishLoading","finally","setCoordinates","cornerCoords","fromLngLat","dMax","getCoordinatesCenterTileID","tileCoords","_boundsArray","boundsBuffer","prepare","boundsSegments","simpleSegment","newTilesLoaded","buckets","VideoSource","muted","onloadstart","getVideo","loop","triggerRepaint","play","pause","seek","seconds","seekableRange","seekable","currentTime","readyState","paused","CanvasSource","animate","getElementById","_hasInvalidDimensions","_playing","getCanvas","registeredSources","getSourceType","DictionaryCoder","strings","_stringToNumber","_numberToString","encode","GeoJSONFeature","vectorTileFeature","_vectorTileFeature","_z","_x","_y","evaluateProperties","serializedProperties","styleLayerProperties","getBounds","topDownFeatureComparator","grid3D","featureIndexArray","loadVTLayers","vtLayers","vt","rawTileData","sourceLayerCoder","sourceFeatureState","featureFilter","queryPadding","matching","cameraBounds","matching3D","bx1","by1","bx2","by2","boxX1","boxY1","boxX2","boxY2","corner","polygonIntersectsBox","previousIndex","featureGeometry","loadMatchingFeature","filterLayerIDs","layerIDs","bucketLayerIDs","arraysIntersect","sourceLayerName","getId","serializedLayer","intersectionZ","geojsonFeature","layerResult","lookupSymbolFeatures","symbolFeatureIndexes","symbolFeatureIndex","hasLayer","sourceLayerId","RTLPluginLoadedEventName","RTLMainThreadPlugin","_syncState","statusToSend","clearRTLTextPlugin","setRTLTextPlugin","url_1","deferred","_requestImport","lazyLoad","rtlMainThreadPlugin","rtlMainThreadPluginFactory","Tile","timeAdded","fadeEndTime","uses","expirationTime","hasSymbolBuckets","dependencies","rtt","rttCoords","expiredRequestCount","registerFadeDuration","wasRequested","clearTextures","justReloaded","hasData","latestFeatureIndex","latestRawTileData","getLayer","lId","deserializeBucket","imageAtlas","glyphAtlasImage","imageAtlasTexture","glyphAtlasTexture","getBucket","querySourceFeatures","_geojsonTileLayer","patternsLoaded","parsedCC","header","$0","$1","$2","$3","maxAge","parseCacheControl","getTime","isExpired","delta","getExpiryTimeout","setFeatureState","sourceLayerStates","holdingForFade","symbolFadeHoldUntil","symbolFadeFinished","clearFadeHold","setHoldDuration","setDependencies","namespace","dep","hasDependency","namespaces","TileCache","reset","removedData","timeout","clearTimeout","order","expiryTimeout","dataWrapper","_getAndRemoveByKey","getAndRemove","getByKey","dataIndex","setMaxSize","filterFn","removed","SourceFeatureState","stateChanges","deletedStates","updateState","featureId","newState","ft","removeFeatureState","reconciledState","featureDeletions","initializeTileState","coalesceChanges","featuresChanged","layerStates","SourceCache","_dataHandler","_sourceErrored","_source","createSource","_tiles","_cache","_unloadTile","_timers","_cacheTimers","_maxTileCacheSize","_maxTileCacheZoomLevels","_loadedParentTiles","_coveredTiles","_didEmitContent","_updated","_sourceLoaded","used","usedForTerrain","getSource","_paused","resume","shouldReload","_shouldReloadOnResume","reload","_loadTile","_tileLoaded","_abortTile","getIds","compareTileId","getRenderableIds","symbolLayer","renderables","_isIdRenderable","a_","b_","rotatedA","rotatedB","hasRenderableParent","parentTile","findLoadedParent","_reloadTile","previousState","refreshedUponExpiration","_setTileReloadTimer","_backfillDEM","borderId","getTileByID","fillBorder","getTile","_retainLoadedChildren","idealTiles","maxCoveringZoom","retain","topmostLoadedID","parentID","minCoveringZoom","parentTileID","_getLoadedTile","findLoadedSibling","updateCacheSize","widthInTiles","heightInTiles","viewDependentMaxSize","handleWrapJump","wrapDelta","_prevLng","_updateCoveredAndRetainedTiles","idealTileIDs","tilesForFading","fadingTiles","siblingTile","fadeTileRef","_addTile","idealRasterTileIDs","missingTileIDs","getVisibleUnwrappedCoordinates","unwrapped","coveringTiles","coveringZoomLevel","maxOverzooming","maxUnderzooming","parents","parent2","noPendingDataEmissions","_updateRetainedTiles","isRasterType","retainedId","keysDifference","_fadeDuration","_removeTile","_updateLoadedParentTileCache","_updateLoadedSiblingTileCache","releaseSymbolFadeTiles","checked","missingTiles","childCoord","childTile","parentWasRequested","parentId","cancelPendingTileRequestsWhileZooming","tileKey","currentId","_loadedSiblingTiles","eventSourceDataType","pointQueryGeometry","tileResults","cameraPointQueryGeometry","getCameraQueryGeometry","pointCoordinate","tileSpaceBounds","tileSpaceQueryGeometry","tileSpaceCameraQueryGeometry","getVisibleCoordinates","posMatrix","reloadTilesForDependencies","aWrap","bWrap","PathInterpolator","points_","padding_","_distances","paddedLength","lerp","distOfCurrentIdx","distToTarget","idxOfPrevPoint","distOfPrevIdx","segmentLength","segmentT","overlapAllowed","overlapA","overlapB","allowed","GridIndex","cellSize","boxCells","circleCells","xCellCount","yCellCount","circleKeys","boxKeys","circles","xScale","yScale","boxUid","circleUid","keysLength","_insertBoxCell","insertCircle","_insertCircleCell","_query","hitTest","overlapMode","predicate","hitTestCircle","_queryCellCircle","queryArgs","boxCell","circleCell","_circleAndRectCollide","_circlesCollide","_convertToXCellCoord","_convertToYCellCoord","r1","r2","bothRadii","circleX","circleY","halfRectWidth","distX","halfRectHeight","distY","getLabelPlaneMatrix","pitchWithMap","rotateWithMap","mat4.rotateZ","labelPlaneMatrix","getGlCoordMatrix","mat4.clone","glCoordMatrix","matrix","getElevation","xyTransformMat4","signedDistanceFromCamera","isOccluded","getPerspectiveRatio","isVisible","clippingBuffer","updateLineLabels","keepUpright","rotateToLine","unwrappedTileID","viewportWidth","viewportHeight","translation","partiallyEvaluatedSize","symbolSize.evaluateSizeForZoom","placedSymbols","aspectRatio","useVertical","hideGlyphs","anchorPos","perspectiveRatio","symbolSize.evaluateSizeForFeature","pitchScaledFontSize","projectionContext","projectionCache","projections","offsets","cachedAnchorPoint","anyProjectionOccluded","tileAnchorPoint","placeUnflipped","placeGlyphsAlongLine","notEnoughRoom","needsFlipping","placeFirstAndLastGlyph","fontScale","flip","glyphEndIndex","lineEndIndex","firstGlyphOffset","lastGlyphOffset","firstPlacedGlyph","placeGlyphAlongLine","lastPlacedGlyph","requiresOrientationChange","firstPoint","lastPoint","placedGlyphs","firstAndLastGlyph","orientationChange","glyphIndex","tileVertexIndex","tileSegmentEnd","projectedVertex","previousTilePoint","currentTilePoint","previousProjectedPoint","minimumLength","projectionMatrix","_projectTruncatedLineSegment","projectTruncatedLineSegmentToLabelPlane","singleGlyph","unitVertexToBeProjected","projectedUnitVertex","projectTileCoordinatesToViewport","projectedUnitSegment","projectLineVertexToViewport","syntheticVertexArgs","previousLineVertexIndex","direction","projectTruncatedLineSegmentToViewport","distanceFromAnchor","previousVertex","absOffsetX","translatedX","translatedY","useSpecialProjectionForSymbols","projectTileCoordinates","transformToOffsetNormal","segmentVector","findOffsetIntersectionPoint","prevToCurrentOffsetNormal","offsetPreviousVertex","offsetCurrentVertex","currentToNextOffsetNormal","offsetNextSegmentBegin","offsetNextSegmentEnd","aDeltaY","aDeltaX","bDeltaY","bDeltaX","denominator","aInterpolation","findLineIntersection","offsetX","anchorSegment","combinedOffsetX","offsetIntersectionPoint","currentSegmentDistance","pathVertices","currentLineSegment","prevToCurrent","segmentAngle","hiddenGlyphAttributes","viewportPadding","CollisionIndex","ignoredGrid","mapProjection","pitchFactor","_pitch","screenRightBoundary","screenBottomBoundary","gridRightBoundary","gridBottomBoundary","perspectiveRatioCutoff","placeCollisionBox","collisionBox","textPixelRatio","collisionGroupPredicate","projectedPoint","projectAndGetPerspectiveRatio","tileToViewport","projectedBox","_projectCollisionBox","pointX","pointY","allPointsOccluded","isInsideGrid","placeable","offscreen","isOffscreen","placeCollisionCircles","labelToScreenMatrix","showCollisionCircles","circlePixelDiameter","textPixelPadding","placedCollisionCircles","tileUnitAnchorPoint","labelPlaneFontScale","projection.placeFirstAndLastGlyph","collisionDetected","inGrid","entirelyOffscreen","screenPlaneMin","screenPlaneMax","interpolator","projectedPath","circleDist","screenSpacePath","projectPathToScreenSpace","minPoint","maxPoint","clippedLines","clippedLine","p0","clipLine","seg","numCircles","circlePosition","centerX","centerY","projection.project","queryRenderedSymbols","viewportQueryGeometry","gridPoint","seenFeatures","featureKey","bucketInstanceId","intersectionTests.polygonIntersectsPolygon","insertCollisionBox","ignorePlacement","collisionGroupID","insertCollisionCircles","collisionCircles","_unwrappedTileID","projection.xyTransformMat4","getViewportMatrix","vecEast","vecSouth","translatedAnchor","toEast","basePoint","distanceMultiplier","zoomFraction","getPitchedTextCorrection","offsetXmin","offsetXmax","offsetXhalf","offsetYmin","offsetYmax","offsetYhalf","offsetsArray","offsetY","anyPointVisible","Anchor","TextAnchorEnum","pixelValue","OpacityState","prevState","increment","placed","skipFade","opacity","JointOpacityState","placedText","placedIcon","JointPlacement","CollisionCircleArray","invProjMatrix","viewportMatrix","RetainedQueryData","CollisionGroups","crossSourceCollisions","maxGroupID","collisionGroups","ID","nextGroupID","calculateVariableLayoutShift","textOffset","Placement","prevPlacement","collisionIndex","placements","opacities","variableOffsets","stale","commitTime","retainedQueryData","collisionCircleArrays","collisionBoxArrays","placedOrientations","_getTerrainElevationFunc","getBucketParts","results","sortAcrossTiles","symbolBucket","bucketFeatureIndex","pixelsToTiles","translationText","translatePosition","translationIcon","textLabelPlaneMatrix","projection.getLabelPlaneMatrix","glMatrix","projection.getGlCoordMatrix","partiallyEvaluatedTextSize","collisionGroup","attemptAnchorPlacement","textAnchorOffset","textOverlapMode","orientation","placedGlyphBoxes","prevAnchor","markUsedJustification","markUsedOrientation","placeLayerBucketPart","bucketPart","seenCrossTileIDs","textOptional","iconOptional","textAlwaysOverlap","iconOverlapMode","iconAlwaysOverlap","hasIconTextFit","zOrderByViewportY","alwaysShowText","alwaysShowIcon","placeSymbol","symbolIndex","placeText","placeIcon","placedVerticalText","placedGlyphCircles","placedIconBoxes","updatePreviousOrientationIfNotPlaced","isPlaced","previousOrientation","prevPlacedOrientation","placeTextForPlacementModes","placeHorizontalFn","placeVerticalFn","placementMode","textAnchorOffsetStart","textAnchorOffsetEnd","placeBox","collisionTextBox","placedFeature","_b","placeBoxForVariableAnchors","collisionIconBox","variableIconBox","placedBox","placementPasses","occluded","prevOrientation","prevOffset","placeIconFeature","iconWithoutText","textWithoutIcon","hasIconBox","storeCollisionData","symbolIndexes","circleArray","mat4.invert","boxArray","realCollisionBox","placedAnchor","autoIndex","getAnchorJustification","indexes","horizontalOnly","horizontalIndexes","commit","zoomAtLastRecencyCheck","placementChanged","prevZoomAdjustment","zoomAdjustment","symbolFadeChange","prevOpacities","prevOffsets","prevOrientations","jointPlacement","prevOpacity","jointOpacity","lastPlacementChangeTime","updateLayerOpacities","updateBucketOpacities","duplicateOpacityState","textAllowOverlap","iconAllowOverlap","hasVariablePlacement","defaultOpacityState","addOpacities","PACKED_HIDDEN_OPACITY","boxArrays","opacityState","horizontalHidden","verticalHidden","packedOpacity","packOpacity","symbolHidden","useHorizontal","realBoxes","variableOffset","updateCollisionVertices","verticalIconUsed","instance","hasTransitions","stillRecent","durationAdjustment","setStale","notUsed","realBox","shiftX","shiftY","shift25","shift24","shift17","shift16","shift9","shift8","shift1","targetBit","opacityBits","createProjection","_t","_transform","_anchor","_tile","_ele","inViewportPixelUnitsUnits","sinA","cosA","getCircleRadiusCorrection","LayerPlacement","_sortAcrossTiles","_currentTileIndex","_currentPartIndex","_seenCrossTileIDs","_bucketParts","continuePlacement","placement","shouldPausePlacement","bucketParts","PauseablePlacement","forceFullPlacement","_currentPlacementIndex","_forceFullPlacement","_showCollisionBoxes","_done","isDone","layerTiles","startTime","placementZoom","_inProgressLayer","ARRAY_TYPES","KDBush","magic","versionAndType","ArrayType","nodeSize","numItems","IndexArrayType","arrayTypeIndex","coordsByteSize","idsByteSize","padCoords","_pos","_finished","numAdded","axis","qy","select","swapItem","roundingFactor","TileLayerIndex","_symbolsByKey","symbolInstancesByKey","instances","symbols","crossTileIDs","getScaledCoordinates","childTileID","localX","localY","localZ","yWorld","yOffset","findMatches","newTileID","zoomCrossTileIDs","scaledSymbolCoord","thisTileSymbol","getCrossTileIDsLists","CrossTileIDs","maxCrossTileID","generate","CrossTileSymbolLayerIndex","usedCrossTileIDs","zoomIndexes","newZoomIndex","addBucket","removeBucketCrossTileIDs","childIndex","parentIndex","removedBucket","removeStaleBuckets","currentIDs","tilesChanged","CrossTileSymbolIndex","layerIndexes","maxBucketInstanceId","bucketsInCurrentPlacement","addLayer","layerIndex","symbolBucketsChanged","currentBucketIDs","pruneUnusedLayers","usedLayers","usedLayerMap","usedLayer","evented","_emitValidationErrors","empty","styleKey","emptyStyle","Style","_rtlPluginLoaded","_getMapId","glyphManager","lineAtlas","crossTileSymbolIndex","_spritesImagesIds","_layers","_order","_availableImages","_resetUpdates","_validateLayer","loadURL","previousStyle","_loadStyleRequest","_load","loadJSON","_frameRequest","loadEmpty","nextState","transformStyle","stylesheet","_loadSprite","_createLayers","setTerrain","dereferencedLayers","_serializedLayers","styledLayer","isUpdate","completion","_spriteRequest","originalSprite","spriteArray","jsonsMap","imagesMap","jsonRequestParameters","imageRequestParameters","spriteName","doOnceCompleted","loadSprite","spriteId","imagesToRemove","_changedImages","imageId","_changed","_unloadSprite","_updatedSources","_serializeByIds","returnClone","serializedLayersDictionary","_serializedAllLayers","toPush","allLayerIds","_checkLoaded","changed","updatedIds","_updatedLayers","removedIds","_removedLayers","_updateWorkerLayers","action","_reloadSource","_clearSource","_updateTilesForChangedImages","_updateTilesForChangedGlyphs","_updatedPaintProps","sourcesUsedBefore","sourceCacheId","sourcesUsedBeforeId","changedImages","_glyphsDidChange","serializedStyle","changes","removeOrAddSourceCommands","diffSources","beforeLayers","beforeOrder","afterOrder","beforeIndex","afterIndex","tracker","clean","beforeLayer","afterLayer","insertBeforeLayerId","lastIndexOf","diffLayers","diffStyles","operations","_getOperationsToPerform","unimplemented","styleChangeOperation","removeLayer","setFilter","setLayerZoomRange","setGeoJSONSourceData","setGlyphs","setSprite","_afterImageUpdated","isSourceLoaded","geojsonSource","layerObject","validateCustomStyleLayer","_layerOrderChanged","_updateLayer","moveLayer","newIndex","getLayersOrder","getFilter","getTerrain","myStyleSheet","_flattenAndSortRenderedFeatures","sourceResults","isLayer3D","features3D","sourceResult","layerFeatures","topmost3D","includedSources","renderedSymbols","bucketQueryData","queryData","bucketSymbols","layerSymbols","sortedA","symbolFeature","layerName","dataTiles","dataID","_update","skyOptions","_remove","_updateSources","_generateCollisionBoxes","_updatePlacement","placementCommitted","layerBucketsChanged","pauseablePlacement","_releaseSymbolFadeTiles","glypgs","getGlyphsUrl","glyphsUrl","addSprite","spriteToAdd","updatedSprite","removeSprite","internalSpriteRepresentation","find","findIndex","getSprite","posAttributes","shaders","prelude","compile","backgroundPattern","clippingMask","heatmapTexture","collisionCircle","debug","fillOutline","fillOutlinePattern","fillPattern","fillExtrusion","fillExtrusionPattern","hillshadePrepare","lineGradient","linePattern","lineSDF","symbolIcon","symbolSDF","symbolTextAndIcon","terrainDepth","terrainCoords","fragmentSource","vertexSource","re","staticAttributes","fragmentUniforms","vertexUniforms","staticUniforms","fragmentPragmas","operation","precision","attrType","unpackType","VertexArrayObject","boundProgram","boundLayoutVertexBuffer","boundPaintVertexBuffers","boundIndexBuffer","boundVertexOffset","boundDynamicVertexBuffer","vao","program","paintVertexBuffers","dynamicVertexBuffer","dynamicVertexBuffer2","dynamicVertexBuffer3","paintBuffersDiffer","boundDynamicVertexBuffer2","boundDynamicVertexBuffer3","freshBind","bindVertexArray","dynamicDraw","numNextAttributes","numAttributes","createVertexArray","enableAttributes","vertexBuffer","setVertexAttribPointers","currentNumAttributes","deleteVertexArray","terrainUniformValues","eleDelta","fogMatrix","u_matrix","u_texture","u_ele_delta","u_fog_matrix","u_fog_color","u_fog_ground_blend","u_fog_ground_blend_opacity","u_horizon_color","u_horizon_fog_blend","getTokenizedAttributesAndUniforms","token","Program","configuration","fixedUniforms","showOverdrawInspector","createProgram","staticAttrInfo","dynamicAttrInfo","allAttrInfo","preludeUniformsInfo","staticUniformsInfo","dynamicUniformsInfo","uniformList","allUniformsInfo","fragmentShader","createShader","FRAGMENT_SHADER","failedToCreate","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","getShaderInfoLog","attachShader","vertexShader","VERTEX_SHADER","attributes","uniformLocations","bindAttribLocation","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","deleteShader","it","uniformLocation","getUniformLocation","terrainUniforms","u_depth","u_terrain","u_terrain_dim","u_terrain_matrix","u_terrain_unpack","u_terrain_exaggeration","terrainPreludeUniforms","drawMode","depthMode","stencilMode","colorMode","cullFaceMode","uniformValues","currentProperties","dynamicLayoutBuffer","dynamicLayoutBuffer2","dynamicLayoutBuffer3","setDepthMode","setStencilMode","setColorMode","setCullFace","activeTexture","TEXTURE2","depthTexture","TEXTURE3","primitiveSize","LINES","TRIANGLES","LINE_STRIP","drawElements","UNSIGNED_SHORT","patternUniformValues","tileRatio","numTiles","tileSizeAtNearestZoom","pixelX","pixelY","u_image","u_texsize","u_scale","u_fade","u_pixel_coord_upper","u_pixel_coord_lower","fillExtrusionUniformValues","shouldUseVerticalGradient","_lp","lightPos","lightMat","mat3.create","mat3.fromRotation","vec3.transformMat3","lightColor","u_lightpos","u_lightintensity","u_lightcolor","u_vertical_gradient","u_opacity","fillExtrusionPatternUniformValues","u_height_factor","fillUniformValues","fillPatternUniformValues","fillOutlineUniformValues","drawingBufferSize","u_world","fillOutlinePatternUniformValues","circleUniformValues","extrudeScale","pixelsToGLUnits","u_camera_to_center_distance","u_scale_with_map","translatePosMatrix","u_pitch_with_map","u_device_pixel_ratio","u_extrude_scale","collisionCircleUniformValues","invMatrix","u_inv_matrix","u_viewport_size","debugUniformValues","scaleRatio","u_color","u_overlay","u_overlay_scale","clippingMaskUniformValues","heatmapUniformValues","u_intensity","heatmapTextureUniformValues","textureUnit","colorRampUnit","mat4.ortho","drawingBufferWidth","drawingBufferHeight","u_color_ramp","getTileLatRange","lineUniformValues","calculateMatrix","u_ratio","u_units_to_pixels","lineGradientUniformValues","imageHeight","u_image_height","linePatternUniformValues","tileZoomRatio","calculateTileRatio","lineSDFUniformValues","posA","posB","widthA","widthB","u_patternscale_a","u_patternscale_b","u_sdfgamma","u_tex_y_a","u_tex_y_b","u_mix","rasterUniformValues","parentTL","parentScaleBy","fade","u_tl_parent","u_scale_parent","u_buffer_scale","u_fade_t","mix","u_image0","u_image1","u_brightness_low","u_brightness_high","u_saturation_factor","saturation","u_contrast_factor","contrast","u_spin_weights","spinWeights","symbolIconUniformValues","rotateInShader","isAlongLine","isVariableAnchor","texSize","pitchedScale","u_is_size_zoom_constant","u_is_size_feature_constant","u_size_t","u_size","u_pitch","u_rotate_symbol","u_aspect_ratio","u_fade_change","u_label_plane_matrix","u_coord_matrix","u_is_text","u_is_along_line","u_is_variable_anchor","u_translation","u_pitched_scale","symbolSDFUniformValues","isHalo","u_gamma_scale","u_is_halo","symbolTextAndIconUniformValues","texSizeSDF","texSizeIcon","u_texsize_icon","u_texture_icon","backgroundUniformValues","backgroundPatternUniformValues","imagePosA","imagePosB","u_pattern_tl_a","u_pattern_br_a","u_pattern_tl_b","u_pattern_br_b","u_pattern_size_a","u_pattern_size_b","u_scale_a","u_scale_b","u_tile_units_to_pixels","bgPatternUniformValues","programUniforms","u_pixel_extrude_scale","u_latrange","u_light","u_shadow","u_highlight","u_accent","u_dimension","u_zoom","u_unpack","u_terrain_coords_id","u_sky_color","u_horizon","u_sky_horizon_blend","IndexBuffer","createBuffer","unbindVAO","bindElementBuffer","bufferData","ELEMENT_ARRAY_BUFFER","DYNAMIC_DRAW","STATIC_DRAW","bufferSubData","deleteBuffer","AttributeType","VertexBuffer","bindVertexBuffer","ARRAY_BUFFER","attribIndex","enableVertexAttribArray","vertexAttribPointer","WeakMap","isWebGL2","getParameter","VERSION","BaseValue","getDefault","setDefault","ClearColor","clearColor","ClearDepth","clearDepth","ClearStencil","clearStencil","ColorMask","colorMask","DepthMask","depthMask","StencilMask","stencilMask","StencilFunc","func","ALWAYS","stencilFunc","StencilOp","KEEP","stencilOp","StencilTest","enable","STENCIL_TEST","disable","DepthRange","depthRange","DepthTest","DEPTH_TEST","DepthFunc","LESS","depthFunc","Blend","BLEND","BlendFunc","ONE","ZERO","blendFunc","BlendColor","blendColor","BlendEquation","FUNC_ADD","blendEquation","CullFace","CULL_FACE","CullFaceSide","BACK","cullFace","FrontFace","CCW","frontFace","ProgramValue","useProgram","ActiveTextureUnit","TEXTURE0","Viewport","BindFramebuffer","bindFramebuffer","FRAMEBUFFER","BindRenderbuffer","bindRenderbuffer","RENDERBUFFER","BindTexture","BindVertexBuffer","bindBuffer","BindElementBuffer","BindVertexArray","getExtension","bindVertexArrayOES","PixelStoreUnpack","pixelStorei","UNPACK_ALIGNMENT","PixelStoreUnpackPremultiplyAlpha","UNPACK_PREMULTIPLY_ALPHA_WEBGL","PixelStoreUnpackFlipY","UNPACK_FLIP_Y_WEBGL","FramebufferAttachment","ColorAttachment","setDirty","framebufferTexture2D","COLOR_ATTACHMENT0","DepthAttachment","framebufferRenderbuffer","DEPTH_ATTACHMENT","DepthStencilAttachment","DEPTH_STENCIL_ATTACHMENT","Framebuffer","hasDepth","hasStencil","framebuffer","createFramebuffer","colorAttachment","depthAttachment","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","renderbuffer","deleteRenderbuffer","deleteFramebuffer","ColorMode","blendFunction","Replace","disabled","unblended","alphaBlended","Context","stencilTest","depthTest","blend","cullFaceSide","extTextureFilterAnisotropic","extTextureFilterAnisotropicMax","MAX_TEXTURE_MAX_ANISOTROPY_EXT","maxTextureSize","MAX_TEXTURE_SIZE","HALF_FLOAT","extColorBufferHalfFloat","RGBA16F","RGBA16F_EXT","RGB16F","RGB16F_EXT","extTextureHalfFloat","HALF_FLOAT_OES","createRenderbuffer","storageFormat","rbo","renderbufferStorage","depth","stencil","COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT","mode","fail","depthFail","createVertexArrayOES","deleteVertexArrayOES","DepthMode","ReadOnly","ReadWrite","StencilMode","CullFaceMode","quadTriangles","drawCollisionDebug","tileBatches","circleCount","circleOffset","invTransform","mat4.mul","colorModeForRenderPass","getTerrainData","circleProgram","vertexData","batch","circleIdx","collision","quadCount","triCount","idx","createQuadTriangles","backCCW","identityMat4","calculateVariableRenderShift","renderTextSize","getShiftedAnchor","projectedAnchorPoint","transformAngle","pitchedTextShiftCorrection","adjustedShift","tileAnchorShifted","symbolProjection.project","east","symbolProjection.projectTileCoordinatesToViewport","updateVariableAnchorsForBucket","tileScale","updateTextFitIcon","dynamicTextLayoutVertexArray","dynamicIconLayoutVertexArray","placedTextShifts","tileAnchor","projectedAnchor","symbolProjection.getPerspectiveRatio","tilePixelRatio","pitchedTextCorrection","shiftedAnchor","symbolProjection.hideGlyphs","placedIcons","getSymbolProgramName","iconsInText","drawLayerSymbols","rotationAlignment","pitchAlignment","isViewportLine","hasSortKey","depthModeForSublayer","tileRenderState","pitchedTextRescaling","programConfiguration","sdfIcons","transformed","terrainData","atlasInterpolation","atlasInterpolationIcon","atlasTextureIcon","rotating","zooming","NEAREST","iconScaled","iconsNeedLinear","baseMatrix","symbolProjection.getLabelPlaneMatrix","glCoordMatrixForShader","symbolProjection.getGlCoordMatrix","glCoordMatrixForSymbolPlacement","hasVariableAnchors","symbolProjection.updateLineLabels","shaderVariableAnchor","uLabelPlaneMatrix","uglCoordMatrix","hasHalo","oldSegments","segmentState","TEXTURE1","drawSymbolElements","prepareHeatmapTerrain","createHeatmapFbo","renderHeatmapTerrain","getColorRampTexture","rasterBoundsBuffer","quadTriangleIndexBuffer","rasterBoundsSegments","numType","internalFormat","updatePatternPositionsInProgram","drawFillTiles","isOutline","fillPropertyName","programName","terrainCoord","tileMatrix","stencilModeForClipping","drawExtrusionTiles","renderHillshade","shadow","highlight","accent","moving","hillshadeUniformValues","prepareHillshade","textureStride","pixelData","renderTexture","hillshadeUniformPrepareValues","getFadeValues","sinceTile","sinceParent","idealZ","fadeIn","childOpacity","topColor","btmColor","leftColor","rightColor","centerColor","drawHorizontalLine","drawDebugSSRect","drawVerticalLine","SCISSOR_TEST","scissor","drawDebugTile","tileRawData","tileSizeKb","tileIdText","initDebugOverlayCanvas","debugOverlayCanvas","ctx2d","shadowColor","shadowBlur","strokeStyle","strokeText","debugOverlayTexture","drawTextToOverlay","debugBuffer","debugSegments","tileBorderIndexBuffer","drawTerrain","LEQUAL","depthRangeFor3D","mesh","getTerrainMesh","renderToTexture","getTexture","getMeshFrameDelta","calculateFogMatrix","Mesh","Painter","_tileTextures","terrainFacilitator","renderTime","setup","numSublayers","depthEpsilon","tileExtentArray","tileExtentBuffer","tileExtentSegments","debugArray","rasterBoundsArray","viewportArray","viewportBuffer","viewportSegments","tileLineStripIndices","quadTriangleIndices","stencilClearMode","nextStencilID","currentStencilSource","_renderTileClippingMasks","tileIDs","_tileClippingMaskIDs","REPLACE","stencilModeFor3D","NOTEQUAL","EQUAL","stencilConfigForOverlap","minTileZ","stencilValues","zToStencilMode","GEQUAL","_showOverdrawInspector","CONSTANT_COLOR","renderPass","opaquePassEnabledForLayer","currentLayer","opaquePassCutoff","coordsAscending","coordsDescending","coordsDescendingSymbol","reverse","maybeDrawDepthAndCoords","prepareForRender","renderLayer","skyUniforms","getHorizon","skyUniformValues","drawSky","showTileBoundaries","selectedSource","flatMap","vectorSources","otherSources","considerSource","selectDebugSource","drawDebug","showPadding","centerPoint","drawCrosshair","drawDebugPadding","requireExact","prevMatrix","currMatrix","modelViewProjectionMatrix","doUpdate","a3","a4","a5","a6","a7","a8","a9","a14","a15","b4","b5","b6","b7","b8","b9","b12","b13","b14","b15","glMatrix.EPSILON","mat4.equals","tilesAfterTime","mat4.copy","getRenderableTiles","getFramebuffer","devicePixelRatio","drawDepth","getCoordsTexture","coordsIndex","drawCoords","pixelToTileScale","updateVariableAnchors","drawSymbols","strokeWidth","strokeOpacity","segmentsRenderStates","segmentsState","drawCircles","prepareHeatmapFlat","renderHeatmapFlat","drawHeatmap","gradient","programId","firstTile","prevProgram","programChanged","atlas","layerGradient","gradientTexture","textureResolution","potentialOverzoom","drawLine","drawFill","drawFillExtrusion","stencilModes","drawHillshade","textureFilter","texParameterf","TEXTURE_MAX_ANISOTROPY_EXT","drawRaster","isPatternMissing","drawBackground","setCustomLayerDefaults","customLayerMatrix","setBaseState","farZ","nearZ","fov","_fov","drawCustom","translatedMatrix","textures","overLimit","Frustum","planes","invProj","frustumCoords","vec4.mul","frustumPlanes","vec3.normalize","az","bz","vec3.cross","vec3.sub","Aabb","min_","max_","vec3.scale","vec3.add","quadrant","qMin","vec3.clone","qMax","distanceX","distanceY","frustum","aabbPoints","fullyInside","plane","pointsInside","projMin","MAX_VALUE","projMax","EdgeInsets","MAX_VALID_LATITUDE","Transform","minPitch","maxPitch","renderWorldCopies","_renderWorldCopies","_minZoom","_maxZoom","_minPitch","_maxPitch","setMaxBounds","_center","_elevation","_unmodified","_edgeInsets","_posMatrixCache","_alignedPosMatrixCache","_fogMatrixCache","minElevationForCurrentTile","that","latRange","lngRange","_calcMatrices","centerOffset","rotationMatrix","mat2.create","mat2.rotate","_zoom","constrainedZoom","zoomScale","_constrain","elevation","isPaddingEqual","interpolatePadding","scaleZoom","utl","utr","ubl","ubr","w0","w1","extraWorldCopy","actualZ","cameraCoord","getCameraPoint","centerCoord","cameraPoint","cameraFrustum","fromInvProjectionMatrix","invModelViewProjectionMatrix","radiusOfMaxLvlLodInTiles","newRootTile","aabb","fullyVisible","intersectResult","refPoint","longestDim","distanceSq","vec2.sqrLen","tileDistanceToCamera","childX","childY","childZ","minMax","getMinMaxElevation","minElevation","maxElevation","unmodified","unproject","getCameraPosition","pointLocation","_pixelPerMeter","recalculateZoom","origElevation","origAltitude","getElevationForLngLatZoom","requiredAltitude","requiredWorldSize","setLocationAtPoint","loc","locationCoordinate","newCenter","coordinateLocation","locationPoint","coordinatePoint","pixelMatrix3D","coordinate","coord0","coord1","pixelMatrixInverse","z0","z1","pixelMatrix","getMaxBounds","calculateTileMatrix","unwrappedX","worldMatrix","aligned","posMatrixKey","alignedModelViewProjectionMatrix","mercatorMatrix","getConstrained","almost180","scaleY","scaleX","screenWidth","screenHeight","originalX","originalY","modifiedX","modifiedY","newPoint","h2","wrappedX","_constraining","cameraToSeaLevelDistance","cameraToLowestPointDistance","lowestPlane","groundAngle","fovAboveCenter","topHalfSurfaceDistance","horizon","fovCenterToHorizon","topHalfSurfaceDistanceHorizon","topHalfMinDistance","mat4.perspective","mat4.rotateX","xShift","yShift","angleCos","angleSin","alignedM","lngLatToCameraDepth","throttle","time","lastCallArgs","pending","timerId","lastCallContext","later","Hash","hashName","_getCurrentHash","hash","_hashName","keyval","_onHashChange","_map","dragRotate","isEnabled","touchZoomRotate","getBearing","jumpTo","_updateHashUnthrottled","getHashString","history","replaceState","_removeHash","currentHash","baseHash","targetHash","replaceString","_updateHash","encodeURIComponent","addTo","mapFeedback","getZoom","getPitch","found","parts","defaultInertiaOptions","linearity","easing","defaultPanInertiaOptions","deceleration","maxSpeed","defaultZoomInertiaOptions","defaultBearingInertiaOptions","defaultPitchInertiaOptions","HandlerInertia","_inertiaBuffer","record","settings","_drainInertiaBuffer","inertia","_onMoveEnd","panInertiaOptions","deltas","pan","pinchAround","around","zoomDelta","bearingDelta","pitchDelta","panDelta","easeOptions","calculateEasing","amount","extendDuration","noMoveStart","inertiaDuration","inertiaOptions","speed","MapMouseEvent","_defaultPrevented","defaultPrevented","originalEvent","mousePos","MapTouchEvent","changedTouches","touchPos","getCanvasContainer","lngLats","curr","MapWheelEvent","MapEventHandler","_clickTolerance","clickTolerance","_mousedownPos","wheel","_firePreventable","mousedown","mouseup","click","dblclick","mouseover","mouseout","touchstart","touchmove","touchend","touchcancel","mapEvent","isActive","BlockableMapEventHandler","_delayContextMenu","_ignoreContextMenu","_contextMenuEvent","mousemove","contextmenu","TransformProvider","_requestedCameraState","BoxZoomHandler","_tr","_el","_container","getContainer","_enabled","_active","shiftKey","disableDrag","_startPos","_lastPos","mousemoveWindow","_box","classList","_fireEvent","setTransform","mouseupWindow","suppressClick","cameraAnimation","fitScreenCoordinates","keydown","keyCode","enableDrag","indexTouches","SingleTapRecognizer","numTouches","mapTouches","timeStamp","getCentroid","newTouches","TapRecognizer","singleTap","numTaps","lastTime","lastTap","count","tap","soonEnough","closeEnough","TapZoomHandler","_zoomIn","_zoomOut","zoomInPoint","zoomOutPoint","easeTo","DragHandler","_moveStateManager","moveStateManager","_moveFunction","move","_activateOnStart","activateOnStart","assignEvents","_moved","_lastPoint","endMove","_move","dragStart","isValidStartEvent","startMove","dragMove","isValidMoveEvent","movePoint","dragEnd","isValidEndEvent","getClickTolerance","BUTTONS_FLAGS","MouseMoveStateManager","_correctEvent","checkCorrectEvent","eventButton","mouseButton","_eventButton","_e","flag","buttons","buttonNoLongerPressed","OneFingerTouchMoveStateManager","_firstTouch","_isOneFingerTouch","targetTouches","_isSameTouchEvent","generateMouseRotationHandler","bearingDegreesPerPixelMoved","mouseMoveStateManager","ctrlKey","generateMousePitchHandler","pitchDegreesPerPixelMoved","TouchPanHandler","_touches","_sum","_shouldBePrevented","touchesCount","cooperativeGestures","_calculateTransform","notifyGestureBlocked","touchPointSum","touchDeltaSum","touchDeltaCount","prevPoint","TwoFingersTouchHandler","_firstTwoTouches","_start","getTouchById","_aroundCenter","getZoomDelta","lastDistance","TwoFingersTouchZoomHandler","_distance","_startDistance","getBearingDelta","TwoFingersTouchRotateHandler","_minDiameter","_startVector","_vector","lastVector","_isBelowThreshold","bearingDeltaSinceStart","isVertical","TwoFingersTouchPitchHandler","_currentTouchCount","_valid","_firstMove","_lastPoints","vectorA","vectorB","gestureBeginsVertically","movedA","movedB","isSameDirection","defaultOptions","panStep","bearingStep","pitchStep","KeyboardHandler","stepOptions","_panStep","_bearingStep","_pitchStep","_rotationDisabled","altKey","metaKey","zoomDir","bearingDir","pitchDir","xDir","yDir","easeId","easeOut","disableRotation","enableRotation","wheelZoomDelta","ScrollZoomHandler","triggerRenderFrame","_onTimeout","initialEvent","_type","_delta","_lastValue","_triggerRenderFrame","_defaultZoomRate","_wheelZoomRate","setZoomRate","zoomRate","setWheelZoomRate","wheelZoomRate","_finishTimeout","isZooming","_zooming","isBypassed","deltaMode","WheelEvent","DOM_DELTA_LINE","deltaY","timeDelta","_lastWheelEventTime","_timeout","_lastWheelEvent","_frameId","_around","_aroundPoint","renderFrame","_targetZoom","_startZoom","_easing","_smoothOutEasing","targetZoom","startZoom","finished","lastWheelEventTimeDiff","noInertia","needsRenderFrame","_prevEase","currentEase","DoubleClickZoomHandler","clickZoom","TapZoom","_clickZoom","_tapZoom","ClickZoomHandler","TapDragZoomHandler","_tap","_swipePoint","_swipeTouch","_tapTime","_tapPoint","swipePoint","newSwipePoint","DragPanHandler","mousePan","touchPan","_mousePan","_touchPan","_inertiaOptions","DragRotateHandler","mouseRotate","mousePitch","_pitchWithRotate","pitchWithRotate","_mouseRotate","_mousePitch","TwoFingersTouchZoomRotateHandler","touchZoom","touchRotate","tapDragZoom","_touchZoom","_touchRotate","_tapDragZoom","CooperativeGesturesHandler","_bypassKey","_setupUI","mapCanvasContainer","desktopMessage","_getUIString","mobileMessage","desktopDiv","textContent","mobileDiv","setAttribute","_destroyUI","gestureType","isMoving","drag","RenderFrameEvent","hasChange","HandlerManager","handleWindowEvent","handleEvent","eventName","_updatingCamera","inputEvent","mergedHandlerResult","eventsInProgress","activeHandlers","eventTouches","_getMapTouches","handlerName","_handlers","_blockedByActive","mergeHandlerResult","deactivatedHandlers","_previousActiveHandlers","_changes","_stop","_inertia","_fireEvents","_handlersById","_bearingSnap","bearingSnap","_eventsInProgress","_addDefaultHandlers","passive","listenerOptions","boxZoom","interactive","tapZoom","doubleClickZoom","touchPitch","generateMousePanHandler","dragPan","scrollZoom","keyboard","allowEndAnimation","isRotating","myName","handlerResult","eventData","_applyChanges","combined","combinedEventsInProgress","combinedDeactivatedHandlers","change","_updateMapTransform","combinedResult","_getTransformForUpdate","_terrainMovement","_elevationFreeze","_applyUpdatedTransform","newEventsInProgress","wasMoving","nowMoving","startEvents","endEvents","originalEndEvent","stillMoving","finishedMoving","inertialEase","shouldSnapToNorth","essential","resetNorth","freezeElevation","_requestFrame","_renderTaskQueue","Camera","_renderFrameCallback","_easeStart","_easeOptions","_onEaseFrame","_easeFrameId","_requestRenderFrame","_moving","setCenter","panBy","panTo","setZoom","zoomTo","zoomIn","zoomOut","setBearing","getPadding","setPadding","rotateTo","resetNorthPitch","snapToNorth","setPitch","cameraForBounds","_cameraForBoxAndBearing","defaultPadding","edgePadding","nwWorld","neWorld","seWorld","swWorld","bearingRadians","nwRotatedWorld","neRotatedWorld","seRotatedWorld","swRotatedWorld","upperRight","lowerLeft","rotatedPaddingOffset","offsetAtFinalZoom","fitBounds","_fitInternal","calculatedOptions","flyTo","zoomChanged","bearingChanged","pitchChanged","calculateCameraOptionsFromTo","altitudeFrom","altitudeTo","fromMerc","toMerc","distance3D","groundDistance","startBearing","startPitch","startPadding","_normalizeBearing","offsetAsPoint","pointAtOffset","locationAtOffset","_normalizeCenter","finalScale","aroundPoint","currently","_rotating","pitching","_pitching","_padding","_easeId","_prepareEase","_prepareElevation","_ease","_updateElevation","speedup","_fireMoveEvents","interruptingEaseId","_finalizeElevation","_afterEase","_elevationCenter","_elevationStart","_elevationTarget","getMinTileElevationForLngLatZoom","pitch1","transformCameraUpdate","_elevateCameraIfInsideTerrain","camera","minAltitude","newCamera","modifiers","finalTransform","modifier","nextTransform","wasZooming","wasRotating","wasPitching","coercedOptions","curve","rho","u1","wMax","rho2","zoomOutFactor","descent","sinh","cosh","r0","S","screenSpeed","maxDuration","isEasing","allowGestures","_cancelRenderFrame","_onEaseEnd","onEaseEnd","handlers","currentBearing","queryTerrainElevation","defaultAttributionControlOptions","compact","customAttribution","AttributionControl","_toggleAttribution","removeAttribute","_updateData","_updateAttributions","_updateCompact","_compact","_updateCompactMinimize","getDefaultPosition","_compactButton","_setElementTitle","_innerContainer","_attribHTML","title","attributions","styleOwner","owner","styleId","attrib","attribHTML","innerHTML","_editLink","LogoControl","containerChildren","rel","display","TaskQueue","_queue","_id","_cleared","_currentlyRunning","cancelled","running","run","PerformanceMarkers","lastFrameTime","frameTimes","frameTimeTarget","loadTimeKey","fullLoadTimeKey","PerformanceUtils","mark","marker","currTimestamp","clearMetrics","clearMeasures","clearMarks","getPerformanceMetrics","measure","fullLoad","loadTime","getEntriesByName","fullLoadTime","totalFrames","fps","droppedFrames","frameTime","percentDroppedFrames","pos3dAttributes","TerrainSourceCache","_renderableTilesKeys","_sourceTileCache","deltaZoom","destruct","freeRtt","getTerrainCoords","_tileID","getSourceTile","searchForDEM","Terrain","qualityFactor","meshSize","_demMatrixCache","_coordsTextureSize","getDEMElevation","vec2.transformMat4","isInBoundsForZoomLngLat","_getOverscaledTileIDFromLngLatZoom","_emptyDemTexture","_emptyDepthTexture","_emptyDemUnpack","_emptyDemMatrix","sourceTile","matrixKey","demMatrix","mat4.fromScaling","_fboDepthTexture","_fbo","_fboCoordsTexture","DEPTH_COMPONENT16","_coordsTexture","fbHeight","readPixels","coordsSize","depthAtPoint","_mesh","meshSize2","offsetTop","offsetBottom","offsetLeft","offsetRight","mercatorCoordinate","tileX","tileY","RenderPool","_context","_size","_tileSize","_objects","_recentlyUsed","_stamp","_createObject","DEPTH_STENCIL","stamp","inUse","getObjectForId","useObject","stampObject","getOrCreateFreeObject","freeObject","freeAllObjects","isFull","LAYERS","RenderToTexture","pool","_stacks","_prevType","_rttTiles","_renderableTiles","_renderableLayerIds","_coordsDescendingInv","_coordsDescendingInvStr","isLastLayer","defaultLocale","packageJSON","attributionControl","maplibreLogo","failIfMajorPerformanceCaveat","preserveDrawingBuffer","refreshExpiredTiles","trackResize","maxTileCacheSize","maxTileCacheZoomLevels","maxCanvasSize","touchmoveWindow","showCompass","showZoom","visualizePitch","MouseRotateWrapper","startMouse","moveMouse","offTemp","startTouch","moveTouch","mapRotateTolerance","mapPitchTolerance","touchMoveStateManager","generateOneFingerTouchRotationHandler","generateOneFingerTouchPitchHandler","supportsGeolocation","smartWrap","priorPos","originalLngLat","anchorTranslate","applyAnchorClass","prefix","Marker","_onKeyPress","legacyCode","charCode","togglePopup","_onMapClick","targetElement","_element","_popup","isFullyLoaded","_lngLat","_flatPos","_offset","rotation","_rotationAlignment","_rotation","_pitchAlignment","_subpixelPositioning","_updateOpacity","_onMove","_isDragging","_pointerdownPos","_positionDelta","setLngLat","pointerEvents","_onUp","_addDragHandler","_color","_scale","_draggable","draggable","subpixelPositioning","setOpacity","opacityWhenCovered","_defaultMarker","svg","createNS","defaultHeight","defaultWidth","setAttributeNS","markerLarge","page1","ellipses","rx","ry","ellipse","bgPath","borderPath","maki","circleContainer","circle1","circle2","setDraggable","_opacityTimeout","getLngLat","getElement","setPopup","popup","_originalTabIndex","markerHeight","markerRadius","linearOffset","SQRT2","getAttribute","setSubpixelPositioning","getPopup","_opacityWhenCovered","isOpen","force","_opacity","terrainDistance","metersToCenter","elevationToCenter","terrainDistanceCenter","centerIsInvisible","getOffset","setOffset","addClassName","removeClassName","toggleClassName","toggle","shouldBeDraggable","isDraggable","setRotation","getRotation","setRotationAlignment","getRotationAlignment","setPitchAlignment","getPitchAlignment","positionOptions","enableHighAccuracy","maximumAge","fitBoundsOptions","trackUserLocation","showAccuracyCircle","showUserLocation","numberOfWatches","noTimeout","updateScale","clientHeight","maxMeters","maxFeet","setScale","maxDistance","pow10","multiplier","getDecimalRoundNum","getRoundNum","closeButton","closeOnClick","focusAfterOpen","focusQuerySelector","normalizeOffset","cornerOffset","convertedOffset","_onFullscreenChange","fullscreenElement","mozFullScreenElement","webkitFullscreenElement","msFullscreenElement","shadowRoot","_fullscreen","_handleFullscreenChange","_onClickFullscreen","_isFullscreen","_exitFullscreen","_requestFullscreen","HTMLElement","_fullscreenchange","_controlContainer","_fullscreenButton","_updateTitle","_getTitle","_prevCooperativeGesturesEnabled","exitFullscreen","mozCancelFullScreen","msExitFullscreen","webkitCancelFullScreen","_togglePseudoFullScreen","requestFullscreen","mozRequestFullScreen","msRequestFullscreen","webkitRequestFullscreen","_onSuccess","_isOutOfMapMaxBounds","_setErrorState","_updateMarker","_finish","_lastKnownPosition","_watchState","_geolocateButton","_updateCamera","_dotElement","longitude","accuracy","newBounds","geolocateSource","_accuracyCircleMarker","_userLocationDotMarker","_accuracy","_updateCircleRadius","_onZoom","_onError","_geolocationWatchID","_clearWatch","_timeoutId","_finishSetupUI","_circleElement","_setup","forceRecalculation","permissions","geolocation","checkGeolocationSupport","clearWatch","southEastPoint","northEastPoint","mapHeightInMeters","circleDiameter","watchPosition","getCurrentPosition","_idleTriggered","_crossFadingFactor","_controls","_contextLost","_contextRestored","_setupPainter","_onMapScroll","scrollTop","scrollLeft","_onWindowOnline","_interactive","_failIfMajorPerformanceCaveat","_preserveDrawingBuffer","_antialias","antialias","_trackResize","_crossSourceCollisions","_locale","_overridePixelRatio","_maxCanvasSize","_imageQueueHandle","maxBounds","_setupContainer","initialResizeEventCaptured","throttledResizeCallback","redraw","_resizeObserver","ResizeObserver","observe","_hash","_localIdeographFontFamily","_validateStyle","setStyle","addControl","logoPosition","control","controlElement","positionContainer","_controlPositions","insertBefore","firstChild","removeControl","ci","hasControl","dimensions","_containerDimensions","clampedPixelRatio","_getClampedPixelRatio","_resizeCanvas","fireMoving","maxCanvasWidth","maxCanvasHeight","canvasWidth","canvasHeight","setPixelRatio","setMinZoom","getMinZoom","setMaxZoom","getMaxZoom","setMinPitch","getMinPitch","setMaxPitch","getMaxPitch","getRenderWorldCopies","setRenderWorldCopies","_createDelegatedListener","mousein","existingLayers","delegates","delegate","_saveDelegatedListener","delegatedListener","_delegatedListeners","_removeDelegatedListener","layerIdsOrListener","geometryOrOptions","isGeometry","_diffStyle","_updateStyle","_lazyInitEmptyStyle","_updateDiff","getStyle","isStyleLoaded","_terrainDataCallback","thisLayer","areTilesLoaded","existingImage","imageData","hasImage","loadImage","beforeId","spriteUrl","_canvasContainer","_canvas","clientWidth","canvasContainer","controlContainer","positionName","webglcontextcreationerrorDetailObject","requestedAttributes","statusMessage","msg","_styleDirty","_sourcesDirty","updateStyle","_render","paintStartTimeStamp","crossFading","_placementDirty","somethingDirty","_repaint","_fullyLoaded","disconnect","loseContext","_showTileBoundaries","_showPadding","repaint","_vertices","getCameraTargetElevation","_updateZoomButtons","isMax","isMin","_zoomInButton","_zoomOutButton","_rotateCompassArrow","_compassIcon","_setButtonTitle","_createButton","_compass","_handler","_content","_onClose","_onMouseMove","_onMouseUp","_onDrag","cursor","_trackPointer","_tip","_closeButton","anchorComponents","offsetedPos","closeOnMove","_focusFirstElement","trackPointer","setText","setDOMContent","createTextNode","setHTML","html","frag","createDocumentFragment","temp","getMaxWidth","setMaxWidth","htmlNode","hasChildNodes","_createCloseButton","firstFocusable","querySelector","focus","setUnit","_toggleTerrain","_updateTerrainIcon","_terrainButton","customProtocol","loadFn","SourceType","setSourceType","workerUrl","numRequests","lazy"],"mappings":";;;;gQAkHO,SAASA,EAAUC,EAASC,EAAYC,EAAGC,GAE9C,OAAO,IAAKD,IAAMA,EAAIE,WAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,GAAQ,CAAG,MAAOG,GAAKL,EAAOK,GAAO,CAC3F,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,GAAU,CAAC,MAAOG,GAAKL,EAAOK,GAAO,CAC9F,SAASF,EAAKI,GAJlB,IAAeL,EAIaK,EAAOC,KAAOT,EAAQQ,EAAOL,QAJ1CA,EAIyDK,E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