{"version":3,"file":"mapbox-gl-csp.js","sources":["../node_modules/@mapbox/mapbox-gl-supported/index.js","../node_modules/@mapbox/unitbezier/index.js","../node_modules/@mapbox/point-geometry/index.js","../src/style-spec/util/deep_equal.js","../src/util/util.js","../src/util/browser.js","../src/util/dom.js","../src/util/config.js","../src/util/webp_supported.js","../src/util/sku_token.js","../src/util/mapbox.js","../src/util/tile_request_cache.js","../src/util/ajax.js","../src/util/evented.js","../src/style-spec/error/validation_error.js","../src/style-spec/validate/validate_constants.js","../src/style-spec/util/extend.js","../src/style-spec/util/unbundle_jsonlint.js","../src/style-spec/expression/parsing_error.js","../src/style-spec/expression/scope.js","../src/style-spec/expression/types.js","../node_modules/csscolorparser/csscolorparser.js","../src/style-spec/util/color.js","../src/style-spec/expression/types/collator.js","../src/style-spec/expression/types/formatted.js","../src/style-spec/expression/values.js","../src/style-spec/expression/definitions/literal.js","../src/style-spec/expression/runtime_error.js","../src/style-spec/expression/definitions/assertion.js","../src/style-spec/expression/definitions/format.js","../src/style-spec/expression/definitions/coercion.js","../src/style-spec/expression/evaluation_context.js","../src/style-spec/expression/compound_expression.js","../src/style-spec/expression/definitions/collator.js","../src/style-spec/expression/is_constant.js","../src/style-spec/expression/definitions/var.js","../src/style-spec/expression/parsing_context.js","../src/style-spec/expression/stops.js","../src/style-spec/expression/definitions/step.js","../src/style-spec/util/interpolate.js","../src/style-spec/util/color_spaces.js","../src/style-spec/expression/definitions/interpolate.js","../src/style-spec/expression/definitions/coalesce.js","../src/style-spec/expression/definitions/let.js","../src/style-spec/expression/definitions/at.js","../src/style-spec/expression/definitions/match.js","../src/style-spec/expression/definitions/case.js","../src/style-spec/expression/definitions/comparison.js","../src/style-spec/expression/definitions/number_format.js","../src/style-spec/expression/definitions/length.js","../src/style-spec/expression/definitions/index.js","../src/style-spec/util/result.js","../src/style-spec/util/properties.js","../src/style-spec/util/get_type.js","../src/style-spec/function/index.js","../src/style-spec/expression/index.js","../src/style-spec/validate/validate_object.js","../src/style-spec/validate/validate_array.js","../src/style-spec/validate/validate_number.js","../src/style-spec/validate/validate_function.js","../src/style-spec/validate/validate_expression.js","../src/style-spec/validate/validate_enum.js","../src/style-spec/feature_filter/index.js","../src/style-spec/validate/validate_filter.js","../src/style-spec/validate/validate_property.js","../src/style-spec/validate/validate_paint_property.js","../src/style-spec/validate/validate_layout_property.js","../src/style-spec/validate/validate_layer.js","../src/style-spec/validate/validate_source.js","../src/style-spec/validate/validate_light.js","../src/style-spec/validate/validate_string.js","../src/style-spec/validate/validate.js","../src/style-spec/validate/validate_boolean.js","../src/style-spec/validate/validate_color.js","../src/style-spec/validate/validate_formatted.js","../src/style-spec/validate/validate_glyphs_url.js","../src/style-spec/validate_style.min.js","../src/style/validate_style.js","../node_modules/grid-index/grid-index.js","../src/util/web_worker_transfer.js","../src/style/zoom_history.js","../src/util/is_char_in_unicode_block.js","../src/util/script_detection.js","../src/source/rtl_text_plugin.js","../src/style/evaluation_parameters.js","../src/style/properties.js","../src/style/style_layer.js","../src/util/struct_array.js","../src/data/array_types.js","../src/data/bucket/circle_attributes.js","../src/data/segment.js","../src/shaders/encode_attribute.js","../src/data/feature_position_map.js","../src/render/uniform_binding.js","../src/data/program_configuration.js","../src/data/extent.js","../src/data/load_geometry.js","../src/data/bucket/circle_bucket.js","../src/util/intersection_tests.js","../src/style/query_utils.js","../src/style/style_layer/circle_style_layer_properties.js","../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","../src/style/style_layer/circle_style_layer.js","../src/data/bucket/heatmap_bucket.js","../src/util/image.js","../src/style/style_layer/heatmap_style_layer_properties.js","../src/util/color_ramp.js","../src/style/style_layer/heatmap_style_layer.js","../src/style/style_layer/hillshade_style_layer_properties.js","../src/style/style_layer/hillshade_style_layer.js","../src/data/bucket/fill_attributes.js","../node_modules/earcut/src/earcut.js","../node_modules/quickselect/index.js","../src/util/classify_rings.js","../src/data/bucket/pattern_bucket_features.js","../src/data/bucket/fill_bucket.js","../src/style/style_layer/fill_style_layer_properties.js","../src/style/style_layer/fill_style_layer.js","../src/data/bucket/fill_extrusion_attributes.js","../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.js","../src/style/style_layer/fill_extrusion_style_layer_properties.js","../src/style/style_layer/fill_extrusion_style_layer.js","../src/data/bucket/line_attributes.js","../src/data/bucket/line_bucket.js","../src/style/style_layer/line_style_layer_properties.js","../src/style/style_layer/line_style_layer.js","../src/data/bucket/symbol_attributes.js","../src/symbol/transform_text.js","../src/util/verticalize_punctuation.js","../src/symbol/shaping.js","../src/symbol/anchor.js","../src/symbol/symbol_size.js","../src/data/bucket/symbol_bucket.js","../src/symbol/mergelines.js","../src/style/style_layer/symbol_style_layer_properties.js","../src/style-spec/expression/definitions/format_section_override.js","../src/style/style_layer/symbol_style_layer.js","../src/util/resolve_tokens.js","../src/style/style_layer/background_style_layer_properties.js","../src/style/style_layer/background_style_layer.js","../src/style/style_layer/raster_style_layer_properties.js","../src/style/style_layer/raster_style_layer.js","../src/style/style_layer/custom_style_layer.js","../src/style/create_style_layer.js","../node_modules/potpack/index.mjs","../src/render/image_atlas.js","../src/render/texture.js","../src/style/style_image.js","../src/render/image_manager.js","../node_modules/ieee754/index.js","../node_modules/pbf/index.js","../src/style/parse_glyph_pbf.js","../node_modules/@mapbox/tiny-sdf/index.js","../src/render/glyph_manager.js","../src/style/load_glyph_range.js","../src/style/light.js","../src/render/line_atlas.js","../src/util/throttled_invoker.js","../src/util/actor.js","../src/util/dispatcher.js","../node_modules/@mapbox/whoots-js/index.mjs","../src/geo/lng_lat_bounds.js","../src/geo/lng_lat.js","../src/geo/mercator_coordinate.js","../src/source/tile_id.js","../src/source/load_tilejson.js","../src/source/tile_bounds.js","../src/source/vector_tile_source.js","../src/source/raster_tile_source.js","../src/data/dem_data.js","../src/source/raster_dem_tile_source.js","../src/source/geojson_source.js","../src/source/image_source.js","../src/source/video_source.js","../src/source/canvas_source.js","../src/source/source.js","../src/source/query_features.js","../src/util/dictionary_coder.js","../src/util/vectortile_to_geojson.js","../src/source/source_state.js","../src/data/feature_index.js","../src/source/tile.js","../src/data/bucket.js","../src/source/tile_cache.js","../src/gl/index_buffer.js","../src/gl/vertex_buffer.js","../src/gl/value.js","../src/gl/framebuffer.js","../src/gl/depth_mode.js","../src/gl/stencil_mode.js","../src/gl/color_mode.js","../src/gl/cull_face_mode.js","../src/gl/context.js","../src/source/source_cache.js","../src/util/browser/web_worker.js","../src/util/worker_pool.js","../src/util/global_worker_pool.js","../src/style-spec/util/ref_properties.js","../src/style-spec/deref.js","../src/style-spec/diff.js","../src/symbol/grid_index.js","../src/symbol/projection.js","../src/symbol/collision_index.js","../node_modules/murmurhash-js/murmurhash3_gc.js","../node_modules/murmurhash-js/index.js","../node_modules/murmurhash-js/murmurhash2_gc.js","../src/symbol/symbol_layout.js","../src/source/pixels_to_tile_units.js","../src/symbol/placement.js","../src/style/pauseable_placement.js","../src/symbol/cross_tile_symbol_index.js","../src/style/style.js","../src/style/load_sprite.js","../src/data/pos_attributes.js","../src/shaders/shaders.js","../src/render/vertex_array_object.js","../src/render/program.js","../src/render/program/pattern.js","../src/render/program/fill_extrusion_program.js","../node_modules/gl-matrix/esm/mat3.js","../src/render/program/fill_program.js","../src/render/program/circle_program.js","../src/render/program/collision_program.js","../src/render/program/debug_program.js","../src/render/program/clipping_mask_program.js","../src/render/program/heatmap_program.js","../src/render/program/hillshade_program.js","../src/render/program/line_program.js","../src/render/program/raster_program.js","../src/render/program/symbol_program.js","../src/render/program/background_program.js","../src/render/program/program_uniforms.js","../src/render/tile_mask.js","../src/render/draw_collision_debug.js","../src/render/draw_symbol.js","../src/render/draw_fill.js","../src/render/draw_fill_extrusion.js","../src/render/draw_hillshade.js","../src/render/draw_raster.js","../src/render/draw_debug.js","../src/render/painter.js","../src/render/draw_circle.js","../src/render/draw_heatmap.js","../src/render/draw_line.js","../src/render/draw_background.js","../src/render/draw_custom.js","../src/util/tile_cover.js","../src/geo/transform.js","../node_modules/gl-matrix/esm/mat2.js","../src/ui/hash.js","../src/util/throttle.js","../src/ui/events.js","../src/ui/handler/scroll_zoom.js","../src/ui/handler/box_zoom.js","../src/ui/handler/drag_rotate.js","../src/ui/handler/drag_pan.js","../src/ui/handler/keyboard.js","../src/ui/handler/dblclick_zoom.js","../src/ui/handler/touch_zoom_rotate.js","../src/ui/bind_handlers.js","../src/ui/camera.js","../src/ui/control/attribution_control.js","../src/ui/control/logo_control.js","../src/util/task_queue.js","../src/ui/map.js","../src/ui/control/navigation_control.js","../src/util/smart_wrap.js","../src/ui/anchor.js","../src/ui/marker.js","../src/ui/control/geolocate_control.js","../src/ui/control/scale_control.js","../src/ui/control/fullscreen_control.js","../src/ui/popup.js","../src/index.js"],"sourcesContent":["'use strict';\n\nif (typeof module !== 'undefined' && module.exports) {\n module.exports = isSupported;\n} else if (window) {\n window.mapboxgl = window.mapboxgl || {};\n window.mapboxgl.supported = isSupported;\n}\n\n/**\n * Test whether the current browser supports Mapbox GL JS\n * @param {Object} options\n * @param {boolean} [options.failIfMajorPerformanceCaveat=false] Return `false`\n * if the performance of Mapbox GL JS would be dramatically worse than\n * expected (i.e. a software renderer is would be used)\n * @return {boolean}\n */\nfunction isSupported(options) {\n return !!(\n isBrowser() &&\n isArraySupported() &&\n isFunctionSupported() &&\n isObjectSupported() &&\n isJSONSupported() &&\n isWorkerSupported() &&\n isUint8ClampedArraySupported() &&\n isArrayBufferSupported() &&\n isWebGLSupportedCached(options && options.failIfMajorPerformanceCaveat)\n );\n}\n\nfunction isBrowser() {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nfunction isArraySupported() {\n return (\n Array.prototype &&\n Array.prototype.every &&\n Array.prototype.filter &&\n Array.prototype.forEach &&\n Array.prototype.indexOf &&\n Array.prototype.lastIndexOf &&\n Array.prototype.map &&\n Array.prototype.some &&\n Array.prototype.reduce &&\n Array.prototype.reduceRight &&\n Array.isArray\n );\n}\n\nfunction isFunctionSupported() {\n return Function.prototype && Function.prototype.bind;\n}\n\nfunction isObjectSupported() {\n return (\n Object.keys &&\n Object.create &&\n Object.getPrototypeOf &&\n Object.getOwnPropertyNames &&\n Object.isSealed &&\n Object.isFrozen &&\n Object.isExtensible &&\n Object.getOwnPropertyDescriptor &&\n Object.defineProperty &&\n Object.defineProperties &&\n Object.seal &&\n Object.freeze &&\n Object.preventExtensions\n );\n}\n\nfunction isJSONSupported() {\n return 'JSON' in window && 'parse' in JSON && 'stringify' in JSON;\n}\n\nfunction isWorkerSupported() {\n if (!('Worker' in window && 'Blob' in window && 'URL' in window)) {\n return false;\n }\n\n var blob = new Blob([''], { type: 'text/javascript' });\n var workerURL = URL.createObjectURL(blob);\n var supported;\n var worker;\n\n try {\n worker = new Worker(workerURL);\n supported = true;\n } catch (e) {\n supported = false;\n }\n\n if (worker) {\n worker.terminate();\n }\n URL.revokeObjectURL(workerURL);\n\n return supported;\n}\n\n// IE11 only supports `Uint8ClampedArray` as of version\n// [KB2929437](https://support.microsoft.com/en-us/kb/2929437)\nfunction isUint8ClampedArraySupported() {\n return 'Uint8ClampedArray' in window;\n}\n\n// https://github.com/mapbox/mapbox-gl-supported/issues/19\nfunction isArrayBufferSupported() {\n return ArrayBuffer.isView;\n}\n\nvar isWebGLSupportedCache = {};\nfunction isWebGLSupportedCached(failIfMajorPerformanceCaveat) {\n\n if (isWebGLSupportedCache[failIfMajorPerformanceCaveat] === undefined) {\n isWebGLSupportedCache[failIfMajorPerformanceCaveat] = isWebGLSupported(failIfMajorPerformanceCaveat);\n }\n\n return isWebGLSupportedCache[failIfMajorPerformanceCaveat];\n}\n\nisSupported.webGLContextAttributes = {\n antialias: false,\n alpha: true,\n stencil: true,\n depth: true\n};\n\nfunction isWebGLSupported(failIfMajorPerformanceCaveat) {\n\n var canvas = document.createElement('canvas');\n\n var attributes = Object.create(isSupported.webGLContextAttributes);\n attributes.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat;\n\n if (canvas.probablySupportsContext) {\n return (\n canvas.probablySupportsContext('webgl', attributes) ||\n canvas.probablySupportsContext('experimental-webgl', attributes)\n );\n\n } else if (canvas.supportsContext) {\n return (\n canvas.supportsContext('webgl', attributes) ||\n canvas.supportsContext('experimental-webgl', attributes)\n );\n\n } else {\n return (\n canvas.getContext('webgl', attributes) ||\n canvas.getContext('experimental-webgl', attributes)\n );\n }\n}\n","/*\n * Copyright (C) 2008 Apple Inc. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Ported from Webkit\n * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h\n */\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 = p2y;\n this.p2x = p2x;\n this.p2y = p2y;\n}\n\nUnitBezier.prototype.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\nUnitBezier.prototype.sampleCurveY = function(t) {\n return ((this.ay * t + this.by) * t + this.cy) * t;\n};\n\nUnitBezier.prototype.sampleCurveDerivativeX = function(t) {\n return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;\n};\n\nUnitBezier.prototype.solveCurveX = function(x, epsilon) {\n if (typeof epsilon === 'undefined') epsilon = 1e-6;\n\n var t0, t1, t2, x2, i;\n\n // First try a few iterations of Newton's method -- normally very fast.\n for (t2 = x, i = 0; i < 8; i++) {\n\n x2 = this.sampleCurveX(t2) - x;\n if (Math.abs(x2) < epsilon) return t2;\n\n var d2 = this.sampleCurveDerivativeX(t2);\n if (Math.abs(d2) < 1e-6) break;\n\n t2 = t2 - x2 / d2;\n }\n\n // Fall back to the bisection method for reliability.\n t0 = 0.0;\n t1 = 1.0;\n t2 = x;\n\n if (t2 < t0) return t0;\n if (t2 > t1) return t1;\n\n while (t0 < t1) {\n\n x2 = this.sampleCurveX(t2);\n if (Math.abs(x2 - x) < epsilon) return t2;\n\n if (x > x2) {\n t0 = t2;\n } else {\n t1 = t2;\n }\n\n t2 = (t1 - t0) * 0.5 + t0;\n }\n\n // Failure.\n return t2;\n};\n\nUnitBezier.prototype.solve = function(x, epsilon) {\n return this.sampleCurveY(this.solveCurveX(x, epsilon));\n};\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","// @flow\n\n/**\n * Deeply compares two object literals.\n *\n * @private\n */\nfunction deepEqual(a: ?mixed, b: ?mixed): 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\nexport default deepEqual;\n","// @flow\n\nimport UnitBezier from '@mapbox/unitbezier';\n\nimport Point from '@mapbox/point-geometry';\nimport window from './window';\n\nimport type {Callback} from '../types/callback';\n\n/**\n * @module util\n * @private\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 *\n * @private\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 * @private\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 function(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 *\n * @private\n */\nexport const ease = 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 * @private\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 * @private\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 * Call an asynchronous function on an array of arguments,\n * calling `callback` with the completed results of all calls.\n *\n * @param array input to each call of the async function.\n * @param fn an async function with signature (data, callback)\n * @param callback a callback run after all async work is done.\n * called with an array, containing the results of each async call.\n * @private\n */\nexport function asyncAll(\n array: Array,\n fn: (item: Item, fnCallback: Callback) => void,\n callback: Callback>\n) {\n if (!array.length) { return callback(null, []); }\n let remaining = array.length;\n const results = new Array(array.length);\n let error = null;\n array.forEach((item, i) => {\n fn(item, (err, result) => {\n if (err) error = err;\n results[i] = ((result: any): Result); // https://github.com/facebook/flow/issues/2123\n if (--remaining === 0) callback(error, results);\n });\n });\n}\n\n/*\n * Polyfill for Object.values. Not fully spec compliant, but we don't\n * need it to be.\n *\n * @private\n */\nexport function values(obj: {[key: string]: T}): Array {\n const result = [];\n for (const k in obj) {\n result.push(obj[k]);\n }\n return result;\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 * @private\n */\nexport function keysDifference(obj: {[key: string]: S}, other: {[key: string]: T}): 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 * @private\n */\nexport function extend(dest: Object, ...sources: Array): Object {\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/**\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 * var foo = { name: 'Charlie', age: 10 };\n * var justName = pick(foo, ['name']);\n * // justName = { name: 'Charlie' }\n * @private\n */\nexport function pick(src: Object, properties: Array): Object {\n const result = {};\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 * @private\n */\nexport function uniqueId(): number {\n return id++;\n}\n\n/**\n * Return a random UUID (v4). Taken from: https://gist.github.com/jed/982883\n * @private\n */\nexport function uuid(): string {\n function b(a) {\n return a ? (a ^ Math.random() * 16 >> a / 4).toString(16) :\n //$FlowFixMe: Flow doesn't like the implied array literal conversion here\n ([1e7] + -[1e3] + -4e3 + -8e3 + -1e11).replace(/[018]/g, b);\n }\n return b();\n}\n\n/**\n * Validate a string to match UUID(v4) of the\n * form: xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx\n * @param str string to validate.\n * @private\n */\nexport function validateUuid(str: ?string): boolean {\n return str ? /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(str) : false;\n}\n\n/**\n * Given an array of member function names as strings, replace all of them\n * with bound versions that will always refer to `context` as `this`. This\n * is useful for classes where otherwise event bindings would reassign\n * `this` to the evented object or some other value: this lets you ensure\n * the `this` value always.\n *\n * @param fns list of member function names\n * @param context the context value\n * @example\n * function MyClass() {\n * bindAll(['ontimer'], this);\n * this.name = 'Tom';\n * }\n * MyClass.prototype.ontimer = function() {\n * alert(this.name);\n * };\n * var myClass = new MyClass();\n * setTimeout(myClass.ontimer, 100);\n * @private\n */\nexport function bindAll(fns: Array, context: Object): void {\n fns.forEach((fn) => {\n if (!context[fn]) { return; }\n context[fn] = context[fn].bind(context);\n });\n}\n\n/**\n * Determine if a string ends with a particular substring\n *\n * @private\n */\nexport function endsWith(string: string, suffix: string): boolean {\n return string.indexOf(suffix, string.length - suffix.length) !== -1;\n}\n\n/**\n * Create an object by mapping all the values of an existing object while\n * preserving their keys.\n *\n * @private\n */\nexport function mapObject(input: Object, iterator: Function, context?: Object): Object {\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 *\n * @private\n */\nexport function filterObject(input: Object, iterator: Function, context?: Object): Object {\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\nimport deepEqual from '../style-spec/util/deep_equal';\nexport { deepEqual };\n\n/**\n * Deeply clones two objects.\n *\n * @private\n */\nexport function clone(input: T): T {\n if (Array.isArray(input)) {\n return input.map(clone);\n } else if (typeof input === 'object' && input) {\n return ((mapObject(input, clone): any): T);\n } else {\n return input;\n }\n}\n\n/**\n * Check if two arrays have at least one common element.\n *\n * @private\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 *\n * @private\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 * @private\n * @returns true for a counter clockwise set of points\n */\n// http://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 * Returns the signed area for the polygon ring. Postive areas are exterior rings and\n * have a clockwise winding. Negative areas are interior rings and have a counter clockwise\n * ordering.\n *\n * @private\n * @param ring Exterior or interior ring\n */\nexport function calculateSignedArea(ring: Array): number {\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/**\n * Detects closed polygons, first + last point are equal\n *\n * @private\n * @param points array of points\n * @return true if the points are a closed polygon\n */\nexport function isClosedPolygon(points: Array): boolean {\n // If it is 2 points that are the same then it is a point\n // If it is 3 points with start and end the same then it is a line\n if (points.length < 4)\n return false;\n\n const p1 = points[0];\n const p2 = points[points.length - 1];\n\n if (Math.abs(p1.x - p2.x) > 0 ||\n Math.abs(p1.y - p2.y) > 0) {\n return false;\n }\n\n // polygon simplification can produce polygons with zero area and more than 3 points\n return Math.abs(calculateSignedArea(points)) > 0.01;\n}\n\n/**\n * Converts spherical coordinates to cartesian coordinates.\n *\n * @private\n * @param spherical Spherical coordinates, in [radial, azimuthal, polar]\n * @return cartesian coordinates in [x, y, z]\n */\n\nexport function sphericalToCartesian([r, azimuthal, polar]: [number, number, number]): {x: number, y: number, z: number} {\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 * Parses data from 'Cache-Control' headers.\n *\n * @private\n * @param cacheControl Value of 'Cache-Control' header\n * @return object containing parsed header info.\n */\n\nexport function parseCacheControl(cacheControl: string): Object {\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\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 window.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(window.atob(str).split('').map((c) => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); //eslint-disable-line\n }).join(''));\n}\n","// @flow strict\n\nimport window from './window';\nimport type { Cancelable } from '../types/cancelable';\n\nconst now = window.performance && window.performance.now ?\n window.performance.now.bind(window.performance) :\n Date.now.bind(Date);\n\nconst raf = window.requestAnimationFrame ||\n window.mozRequestAnimationFrame ||\n window.webkitRequestAnimationFrame ||\n window.msRequestAnimationFrame;\n\nconst cancel = window.cancelAnimationFrame ||\n window.mozCancelAnimationFrame ||\n window.webkitCancelAnimationFrame ||\n window.msCancelAnimationFrame;\n\nlet linkEl;\n\nlet reducedMotionQuery: MediaQueryList;\n\n/**\n * @private\n */\nconst exported = {\n /**\n * Provides a function that outputs milliseconds: either performance.now()\n * or a fallback to Date.now()\n */\n now,\n\n frame(fn: () => void): Cancelable {\n const frame = raf(fn);\n return { cancel: () => cancel(frame) };\n },\n\n getImageData(img: CanvasImageSource): ImageData {\n const canvas = window.document.createElement('canvas');\n const context = canvas.getContext('2d');\n if (!context) {\n throw new Error('failed to create canvas 2d context');\n }\n canvas.width = img.width;\n canvas.height = img.height;\n context.drawImage(img, 0, 0, img.width, img.height);\n return context.getImageData(0, 0, img.width, img.height);\n },\n\n resolveURL(path: string) {\n if (!linkEl) linkEl = window.document.createElement('a');\n linkEl.href = path;\n return linkEl.href;\n },\n\n hardwareConcurrency: window.navigator.hardwareConcurrency || 4,\n\n get devicePixelRatio() { return window.devicePixelRatio; },\n get prefersReducedMotion(): boolean {\n if (!window.matchMedia) return false;\n //Lazily initialize media query\n if (reducedMotionQuery == null) {\n reducedMotionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');\n }\n return reducedMotionQuery.matches;\n },\n};\n\nexport default exported;\n","// @flow strict\n\nimport Point from '@mapbox/point-geometry';\n\nimport window from './window';\nimport assert from 'assert';\n\nconst DOM = {};\nexport default DOM;\n\nDOM.create = function (tagName: string, className: ?string, container?: HTMLElement) {\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\nDOM.createNS = function (namespaceURI: string, tagName: string) {\n const el = window.document.createElementNS(namespaceURI, tagName);\n return el;\n};\n\nconst docStyle = window.document.documentElement.style;\n\nfunction testProp(props) {\n if (!docStyle) return props[0];\n for (let i = 0; i < props.length; i++) {\n if (props[i] in docStyle) {\n return props[i];\n }\n }\n return props[0];\n}\n\nconst selectProp = testProp(['userSelect', 'MozUserSelect', 'WebkitUserSelect', 'msUserSelect']);\nlet userSelect;\n\nDOM.disableDrag = function () {\n if (docStyle && selectProp) {\n userSelect = docStyle[selectProp];\n docStyle[selectProp] = 'none';\n }\n};\n\nDOM.enableDrag = function () {\n if (docStyle && selectProp) {\n docStyle[selectProp] = userSelect;\n }\n};\n\nconst transformProp = testProp(['transform', 'WebkitTransform']);\n\nDOM.setTransform = function(el: HTMLElement, value: string) {\n // https://github.com/facebook/flow/issues/7754\n // $FlowFixMe\n el.style[transformProp] = value;\n};\n\n// Feature detection for {passive: false} support in add/removeEventListener.\nlet passiveSupported = false;\n\ntry {\n // https://github.com/facebook/flow/issues/285\n // $FlowFixMe\n const options = Object.defineProperty({}, \"passive\", {\n get() { // eslint-disable-line\n passiveSupported = true;\n }\n });\n window.addEventListener(\"test\", options, options);\n window.removeEventListener(\"test\", options, options);\n} catch (err) {\n passiveSupported = false;\n}\n\nDOM.addEventListener = function(target: *, type: *, callback: *, options: {passive?: boolean, capture?: boolean} = {}) {\n if ('passive' in options && passiveSupported) {\n target.addEventListener(type, callback, options);\n } else {\n target.addEventListener(type, callback, options.capture);\n }\n};\n\nDOM.removeEventListener = function(target: *, type: *, callback: *, options: {passive?: boolean, capture?: boolean} = {}) {\n if ('passive' in options && passiveSupported) {\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.\nconst suppressClick: MouseEventListener = function (e) {\n e.preventDefault();\n e.stopPropagation();\n window.removeEventListener('click', suppressClick, true);\n};\n\nDOM.suppressClick = function() {\n window.addEventListener('click', suppressClick, true);\n window.setTimeout(() => {\n window.removeEventListener('click', suppressClick, true);\n }, 0);\n};\n\nDOM.mousePos = function (el: HTMLElement, e: MouseEvent | window.TouchEvent | Touch) {\n const rect = el.getBoundingClientRect();\n const t = window.TouchEvent && (e instanceof window.TouchEvent) ? e.touches[0] : e;\n return new Point(\n t.clientX - rect.left - el.clientLeft,\n t.clientY - rect.top - el.clientTop\n );\n};\n\nDOM.touchPos = function (el: HTMLElement, e: TouchEvent) {\n const rect = el.getBoundingClientRect(),\n points = [];\n const touches = (e.type === 'touchend') ? e.changedTouches : e.touches;\n for (let i = 0; i < touches.length; i++) {\n points.push(new Point(\n touches[i].clientX - rect.left - el.clientLeft,\n touches[i].clientY - rect.top - el.clientTop\n ));\n }\n return points;\n};\n\nDOM.mouseButton = function (e: MouseEvent) {\n assert(e.type === 'mousedown' || e.type === 'mouseup');\n if (typeof window.InstallTrigger !== 'undefined' && e.button === 2 && e.ctrlKey &&\n window.navigator.platform.toUpperCase().indexOf('MAC') >= 0) {\n // Fix for https://github.com/mapbox/mapbox-gl-js/issues/3131:\n // Firefox (detected by InstallTrigger) on Mac determines e.button = 2 when\n // using Control + left click\n return 0;\n }\n return e.button;\n};\n\nDOM.remove = function(node: HTMLElement) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n};\n","// @flow strict\n\ntype Config = {|\n API_URL: string,\n EVENTS_URL: ?string,\n FEEDBACK_URL: string,\n REQUIRE_ACCESS_TOKEN: boolean,\n ACCESS_TOKEN: ?string,\n MAX_PARALLEL_IMAGE_REQUESTS: number\n|};\n\nconst config: Config = {\n API_URL: 'https://api.mapbox.com',\n get EVENTS_URL() {\n if (!this.API_URL) { return null; }\n if (this.API_URL.indexOf('https://api.mapbox.cn') === 0) {\n return 'https://events.mapbox.cn/events/v2';\n } else if (this.API_URL.indexOf('https://api.mapbox.com') === 0) {\n return 'https://events.mapbox.com/events/v2';\n } else {\n return null;\n }\n },\n FEEDBACK_URL: 'https://apps.mapbox.com/feedback',\n REQUIRE_ACCESS_TOKEN: true,\n ACCESS_TOKEN: null,\n MAX_PARALLEL_IMAGE_REQUESTS: 16\n};\n\nexport default config;\n","// @flow strict\n\nimport window from './window';\n\nconst exported = {\n supported: false,\n testSupport\n};\n\nexport default exported;\n\nlet glForTesting;\nlet webpCheckComplete = false;\nlet webpImgTest;\nlet webpImgTestOnloadComplete = false;\n\nif (window.document) {\n webpImgTest = window.document.createElement('img');\n webpImgTest.onload = function() {\n if (glForTesting) testWebpTextureUpload(glForTesting);\n glForTesting = null;\n webpImgTestOnloadComplete = true;\n };\n webpImgTest.onerror = function() {\n webpCheckComplete = true;\n glForTesting = null;\n };\n webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=';\n}\n\nfunction testSupport(gl: WebGLRenderingContext) {\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) {\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 exported.supported = true;\n } catch (e) {\n // Catch \"Unspecified Error.\" in Edge 18.\n }\n\n gl.deleteTexture(texture);\n\n webpCheckComplete = true;\n}\n","// @flow\n\n/***** START WARNING - IF YOU USE THIS CODE WITH MAPBOX MAPPING APIS, REMOVAL OR\n* MODIFICATION OF THE FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******\n* The following code is used to access Mapbox's Mapping APIs. Removal or modification\n* of this code when used with Mapbox's Mapping APIs can result in higher fees and/or\n* termination of your account with Mapbox.\n*\n* Under the Mapbox Terms of Service, you may not use this code to access Mapbox\n* Mapping APIs other than through Mapbox SDKs.\n*\n* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps\n* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/\n******************************************************************************/\n\ntype SkuTokenObject = {|\n token: string,\n tokenExpiresAt: number\n|};\n\nconst SKU_ID = '01';\n\nfunction createSkuToken(): SkuTokenObject {\n // SKU_ID and TOKEN_VERSION are specified by an internal schema and should not change\n const TOKEN_VERSION = '1';\n const base62chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n // sessionRandomizer is a randomized 10-digit base-62 number\n let sessionRandomizer = '';\n for (let i = 0; i < 10; i++) {\n sessionRandomizer += base62chars[Math.floor(Math.random() * 62)];\n }\n const expiration = 12 * 60 * 60 * 1000; // 12 hours\n const token = [TOKEN_VERSION, SKU_ID, sessionRandomizer].join('');\n const tokenExpiresAt = Date.now() + expiration;\n\n return { token, tokenExpiresAt };\n}\n\nexport { createSkuToken, SKU_ID };\n\n/***** END WARNING - REMOVAL OR MODIFICATION OF THE\nPRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/\n","// @flow\n\n/***** START WARNING - IF YOU USE THIS CODE WITH MAPBOX MAPPING APIS, REMOVAL OR\n* MODIFICATION OF THE FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******\n* The following code is used to access Mapbox's Mapping APIs. Removal or modification\n* of this code when used with Mapbox's Mapping APIs can result in higher fees and/or\n* termination of your account with Mapbox.\n*\n* Under the Mapbox Terms of Service, you may not use this code to access Mapbox\n* Mapping APIs other than through Mapbox SDKs.\n*\n* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps\n* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/\n******************************************************************************/\n\nimport config from './config';\n\nimport browser from './browser';\nimport window from './window';\nimport webpSupported from './webp_supported';\nimport { createSkuToken, SKU_ID } from './sku_token';\nimport { version as sdkVersion } from '../../package.json';\nimport { uuid, validateUuid, storageAvailable, b64DecodeUnicode, b64EncodeUnicode, warnOnce, extend } from './util';\nimport { postData, ResourceType } from './ajax';\n\nimport type { RequestParameters } from './ajax';\nimport type { Cancelable } from '../types/cancelable';\nimport type { TileJSON } from '../types/tilejson';\n\ntype ResourceTypeEnum = $Keys;\nexport type RequestTransformFunction = (url: string, resourceType?: ResourceTypeEnum) => RequestParameters;\n\ntype UrlObject = {|\n protocol: string,\n authority: string,\n path: string,\n params: Array\n|};\n\nexport class RequestManager {\n _skuToken: string;\n _skuTokenExpiresAt: number;\n _transformRequestFn: ?RequestTransformFunction;\n _customAccessToken: ?string;\n\n constructor(transformRequestFn?: RequestTransformFunction, customAccessToken?: string) {\n this._transformRequestFn = transformRequestFn;\n this._customAccessToken = customAccessToken;\n this._createSkuToken();\n }\n\n _createSkuToken() {\n const skuToken = createSkuToken();\n this._skuToken = skuToken.token;\n this._skuTokenExpiresAt = skuToken.tokenExpiresAt;\n }\n\n _isSkuTokenExpired(): boolean {\n return Date.now() > this._skuTokenExpiresAt;\n }\n\n transformRequest(url: string, type: ResourceTypeEnum) {\n if (this._transformRequestFn) {\n return this._transformRequestFn(url, type) || {url};\n }\n\n return {url};\n }\n\n normalizeStyleURL(url: string, accessToken?: string): string {\n if (!isMapboxURL(url)) return url;\n const urlObject = parseUrl(url);\n urlObject.path = `/styles/v1${urlObject.path}`;\n return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);\n }\n\n normalizeGlyphsURL(url: string, accessToken?: string): string {\n if (!isMapboxURL(url)) return url;\n const urlObject = parseUrl(url);\n urlObject.path = `/fonts/v1${urlObject.path}`;\n return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);\n }\n\n normalizeSourceURL(url: string, accessToken?: string): string {\n if (!isMapboxURL(url)) return url;\n const urlObject = parseUrl(url);\n urlObject.path = `/v4/${urlObject.authority}.json`;\n // TileJSON requests need a secure flag appended to their URLs so\n // that the server knows to send SSL-ified resource references.\n urlObject.params.push('secure');\n return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);\n }\n\n normalizeSpriteURL(url: string, format: string, extension: string, accessToken?: string): string {\n const urlObject = parseUrl(url);\n if (!isMapboxURL(url)) {\n urlObject.path += `${format}${extension}`;\n return formatUrl(urlObject);\n }\n urlObject.path = `/styles/v1${urlObject.path}/sprite${format}${extension}`;\n return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);\n }\n\n normalizeTileURL(tileURL: string, sourceURL?: ?string, tileSize?: ?number): string {\n if (this._isSkuTokenExpired()) {\n this._createSkuToken();\n }\n\n if (!sourceURL || !isMapboxURL(sourceURL)) return tileURL;\n\n const urlObject = parseUrl(tileURL);\n const imageExtensionRe = /(\\.(png|jpg)\\d*)(?=$)/;\n const tileURLAPIPrefixRe = /^.+\\/v4\\//;\n\n // The v4 mapbox tile API supports 512x512 image tiles only when @2x\n // is appended to the tile URL. If `tileSize: 512` is specified for\n // a Mapbox raster source force the @2x suffix even if a non hidpi device.\n const suffix = browser.devicePixelRatio >= 2 || tileSize === 512 ? '@2x' : '';\n const extension = webpSupported.supported ? '.webp' : '$1';\n urlObject.path = urlObject.path.replace(imageExtensionRe, `${suffix}${extension}`);\n urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, '/');\n urlObject.path = `/v4${urlObject.path}`;\n\n if (config.REQUIRE_ACCESS_TOKEN && (config.ACCESS_TOKEN || this._customAccessToken) && this._skuToken) {\n urlObject.params.push(`sku=${this._skuToken}`);\n }\n\n return this._makeAPIURL(urlObject, this._customAccessToken);\n }\n\n canonicalizeTileURL(url: string) {\n const version = \"/v4/\";\n // matches any file extension specified by a dot and one or more alphanumeric characters\n const extensionRe = /\\.[\\w]+$/;\n\n const urlObject = parseUrl(url);\n // Make sure that we are dealing with a valid Mapbox tile URL.\n // Has to begin with /v4/, with a valid filename + extension\n if (!urlObject.path.match(/(^\\/v4\\/)/) || !urlObject.path.match(extensionRe)) {\n // Not a proper Mapbox tile URL.\n return url;\n }\n // Reassemble the canonical URL from the parts we've parsed before.\n let result = \"mapbox://tiles/\";\n result += urlObject.path.replace(version, '');\n\n // Append the query string, minus the access token parameter.\n const params = urlObject.params.filter(p => !p.match(/^access_token=/));\n if (params.length) result += `?${params.join('&')}`;\n return result;\n }\n\n canonicalizeTileset(tileJSON: TileJSON, sourceURL: string) {\n if (!isMapboxURL(sourceURL)) return tileJSON.tiles || [];\n const canonical = [];\n for (const url of tileJSON.tiles) {\n const canonicalUrl = this.canonicalizeTileURL(url);\n canonical.push(canonicalUrl);\n }\n return canonical;\n }\n\n _makeAPIURL(urlObject: UrlObject, accessToken: string | null | void): string {\n const help = 'See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes';\n const apiUrlObject = parseUrl(config.API_URL);\n urlObject.protocol = apiUrlObject.protocol;\n urlObject.authority = apiUrlObject.authority;\n\n if (apiUrlObject.path !== '/') {\n urlObject.path = `${apiUrlObject.path}${urlObject.path}`;\n }\n\n if (!config.REQUIRE_ACCESS_TOKEN) return formatUrl(urlObject);\n\n accessToken = accessToken || config.ACCESS_TOKEN;\n if (!accessToken)\n throw new Error(`An API access token is required to use Mapbox GL. ${help}`);\n if (accessToken[0] === 's')\n throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${help}`);\n\n urlObject.params = urlObject.params.filter((d) => d.indexOf('access_token') === -1);\n urlObject.params.push(`access_token=${accessToken}`);\n return formatUrl(urlObject);\n }\n}\n\nfunction isMapboxURL(url: string) {\n return url.indexOf('mapbox:') === 0;\n}\n\nconst mapboxHTTPURLRe = /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/|\\?|$)/i;\nfunction isMapboxHTTPURL(url: string): boolean {\n return mapboxHTTPURLRe.test(url);\n}\n\nfunction hasCacheDefeatingSku(url: string) {\n return url.indexOf('sku=') > 0 && isMapboxHTTPURL(url);\n}\n\nconst urlRe = /^(\\w+):\\/\\/([^/?]*)(\\/[^?]+)?\\??(.+)?/;\n\nfunction parseUrl(url: string): UrlObject {\n const parts = url.match(urlRe);\n if (!parts) {\n throw new Error('Unable to parse URL object');\n }\n return {\n protocol: parts[1],\n authority: parts[2],\n path: parts[3] || '/',\n params: parts[4] ? parts[4].split('&') : []\n };\n}\n\nfunction formatUrl(obj: UrlObject): string {\n const params = obj.params.length ? `?${obj.params.join('&')}` : '';\n return `${obj.protocol}://${obj.authority}${obj.path}${params}`;\n}\n\nexport { isMapboxURL, isMapboxHTTPURL, hasCacheDefeatingSku };\n\nconst telemEventKey = 'mapbox.eventData';\n\nfunction parseAccessToken(accessToken: ?string) {\n if (!accessToken) {\n return null;\n }\n\n const parts = accessToken.split('.');\n if (!parts || parts.length !== 3) {\n return null;\n }\n\n try {\n const jsonData = JSON.parse(b64DecodeUnicode(parts[1]));\n return jsonData;\n } catch (e) {\n return null;\n }\n}\n\ntype TelemetryEventType = 'appUserTurnstile' | 'map.load';\n\nclass TelemetryEvent {\n eventData: any;\n anonId: ?string;\n queue: Array;\n type: TelemetryEventType;\n pendingRequest: ?Cancelable;\n _customAccessToken: ?string;\n\n constructor(type: TelemetryEventType) {\n this.type = type;\n this.anonId = null;\n this.eventData = {};\n this.queue = [];\n this.pendingRequest = null;\n }\n\n getStorageKey(domain: ?string) {\n const tokenData = parseAccessToken(config.ACCESS_TOKEN);\n let u = '';\n if (tokenData && tokenData['u']) {\n u = b64EncodeUnicode(tokenData['u']);\n } else {\n u = config.ACCESS_TOKEN || '';\n }\n return domain ?\n `${telemEventKey}.${domain}:${u}` :\n `${telemEventKey}:${u}`;\n }\n\n fetchEventData() {\n const isLocalStorageAvailable = storageAvailable('localStorage');\n const storageKey = this.getStorageKey();\n const uuidKey = this.getStorageKey('uuid');\n\n if (isLocalStorageAvailable) {\n //Retrieve cached data\n try {\n const data = window.localStorage.getItem(storageKey);\n if (data) {\n this.eventData = JSON.parse(data);\n }\n\n const uuid = window.localStorage.getItem(uuidKey);\n if (uuid) this.anonId = uuid;\n } catch (e) {\n warnOnce('Unable to read from LocalStorage');\n }\n }\n }\n\n saveEventData() {\n const isLocalStorageAvailable = storageAvailable('localStorage');\n const storageKey = this.getStorageKey();\n const uuidKey = this.getStorageKey('uuid');\n if (isLocalStorageAvailable) {\n try {\n window.localStorage.setItem(uuidKey, this.anonId);\n if (Object.keys(this.eventData).length >= 1) {\n window.localStorage.setItem(storageKey, JSON.stringify(this.eventData));\n }\n } catch (e) {\n warnOnce('Unable to write to LocalStorage');\n }\n }\n\n }\n\n processRequests(_: ?string) {}\n\n /*\n * If any event data should be persisted after the POST request, the callback should modify eventData`\n * to the values that should be saved. For this reason, the callback should be invoked prior to the call\n * to TelemetryEvent#saveData\n */\n postEvent(timestamp: number, additionalPayload: {[string]: any}, callback: (err: ?Error) => void, customAccessToken?: ?string) {\n if (!config.EVENTS_URL) return;\n const eventsUrlObject: UrlObject = parseUrl(config.EVENTS_URL);\n eventsUrlObject.params.push(`access_token=${customAccessToken || config.ACCESS_TOKEN || ''}`);\n\n const payload: Object = {\n event: this.type,\n created: new Date(timestamp).toISOString(),\n sdkIdentifier: 'mapbox-gl-js',\n sdkVersion,\n skuId: SKU_ID,\n userId: this.anonId\n };\n\n const finalPayload = additionalPayload ? extend(payload, additionalPayload) : payload;\n const request: RequestParameters = {\n url: formatUrl(eventsUrlObject),\n headers: {\n 'Content-Type': 'text/plain' //Skip the pre-flight OPTIONS request\n },\n body: JSON.stringify([finalPayload])\n };\n\n this.pendingRequest = postData(request, (error) => {\n this.pendingRequest = null;\n callback(error);\n this.saveEventData();\n this.processRequests(customAccessToken);\n });\n }\n\n queueRequest(event: number | {id: number, timestamp: number}, customAccessToken?: ?string) {\n this.queue.push(event);\n this.processRequests(customAccessToken);\n }\n}\n\nexport class MapLoadEvent extends TelemetryEvent {\n +success: {[number]: boolean};\n skuToken: string;\n\n constructor() {\n super('map.load');\n this.success = {};\n this.skuToken = '';\n }\n\n postMapLoadEvent(tileUrls: Array, mapId: number, skuToken: string, customAccessToken: string) {\n //Enabled only when Mapbox Access Token is set and a source uses\n // mapbox tiles.\n this.skuToken = skuToken;\n\n if (config.EVENTS_URL &&\n customAccessToken || config.ACCESS_TOKEN &&\n Array.isArray(tileUrls) &&\n tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url))) {\n this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken);\n }\n }\n\n processRequests(customAccessToken?: ?string) {\n if (this.pendingRequest || this.queue.length === 0) return;\n const {id, timestamp} = this.queue.shift();\n\n // Only one load event should fire per map\n if (id && this.success[id]) return;\n\n if (!this.anonId) {\n this.fetchEventData();\n }\n\n if (!validateUuid(this.anonId)) {\n this.anonId = uuid();\n }\n\n this.postEvent(timestamp, {skuToken: this.skuToken}, (err) => {\n if (!err) {\n if (id) this.success[id] = true;\n }\n }, customAccessToken);\n }\n}\n\nexport class TurnstileEvent extends TelemetryEvent {\n constructor(customAccessToken?: ?string) {\n super('appUserTurnstile');\n this._customAccessToken = customAccessToken;\n }\n\n postTurnstileEvent(tileUrls: Array, customAccessToken?: ?string) {\n //Enabled only when Mapbox Access Token is set and a source uses\n // mapbox tiles.\n if (config.EVENTS_URL &&\n config.ACCESS_TOKEN &&\n Array.isArray(tileUrls) &&\n tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url))) {\n this.queueRequest(Date.now(), customAccessToken);\n }\n }\n\n processRequests(customAccessToken?: ?string) {\n if (this.pendingRequest || this.queue.length === 0) {\n return;\n }\n\n if (!this.anonId || !this.eventData.lastSuccess || !this.eventData.tokenU) {\n //Retrieve cached data\n this.fetchEventData();\n }\n\n const tokenData = parseAccessToken(config.ACCESS_TOKEN);\n const tokenU = tokenData ? tokenData['u'] : config.ACCESS_TOKEN;\n //Reset event data cache if the access token owner changed.\n let dueForEvent = tokenU !== this.eventData.tokenU;\n\n if (!validateUuid(this.anonId)) {\n this.anonId = uuid();\n dueForEvent = true;\n }\n\n const nextUpdate = this.queue.shift();\n // Record turnstile event once per calendar day.\n if (this.eventData.lastSuccess) {\n const lastUpdate = new Date(this.eventData.lastSuccess);\n const nextDate = new Date(nextUpdate);\n const daysElapsed = (nextUpdate - this.eventData.lastSuccess) / (24 * 60 * 60 * 1000);\n dueForEvent = dueForEvent || daysElapsed >= 1 || daysElapsed < -1 || lastUpdate.getDate() !== nextDate.getDate();\n } else {\n dueForEvent = true;\n }\n\n if (!dueForEvent) {\n return this.processRequests();\n }\n\n this.postEvent(nextUpdate, {\"enabled.telemetry\": false}, (err) => {\n if (!err) {\n this.eventData.lastSuccess = nextUpdate;\n this.eventData.tokenU = tokenU;\n }\n }, customAccessToken);\n }\n}\n\nconst turnstileEvent_ = new TurnstileEvent();\nexport const postTurnstileEvent = turnstileEvent_.postTurnstileEvent.bind(turnstileEvent_);\n\nconst mapLoadEvent_ = new MapLoadEvent();\nexport const postMapLoadEvent = mapLoadEvent_.postMapLoadEvent.bind(mapLoadEvent_);\n\n/***** END WARNING - REMOVAL OR MODIFICATION OF THE\nPRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/\n","// @flow\n\nimport { warnOnce, parseCacheControl } from './util';\nimport window from './window';\n\nimport type Dispatcher from './dispatcher';\n\nconst CACHE_NAME = 'mapbox-tiles';\nlet cacheLimit = 500; // 50MB / (100KB/tile) ~= 500 tiles\nlet cacheCheckThreshold = 50;\n\nconst MIN_TIME_UNTIL_EXPIRY = 1000 * 60 * 7; // 7 minutes. Skip caching tiles with a short enough max age.\n\nexport type ResponseOptions = {\n status: number,\n statusText: string,\n headers: window.Headers\n};\n\nlet responseConstructorSupportsReadableStream;\nfunction prepareBody(response: Response, callback) {\n if (responseConstructorSupportsReadableStream === undefined) {\n try {\n new Response(new ReadableStream()); // eslint-disable-line no-undef\n responseConstructorSupportsReadableStream = true;\n } catch (e) {\n // Edge\n responseConstructorSupportsReadableStream = false;\n }\n }\n\n if (responseConstructorSupportsReadableStream) {\n callback(response.body);\n } else {\n response.blob().then(callback);\n }\n}\n\nexport function cachePut(request: Request, response: Response, requestTime: number) {\n if (!window.caches) return;\n\n const options: ResponseOptions = {\n status: response.status,\n statusText: response.statusText,\n headers: new window.Headers()\n };\n response.headers.forEach((v, k) => options.headers.set(k, v));\n\n const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || '');\n if (cacheControl['no-store']) {\n return;\n }\n if (cacheControl['max-age']) {\n options.headers.set('Expires', new Date(requestTime + cacheControl['max-age'] * 1000).toUTCString());\n }\n\n const timeUntilExpiry = new Date(options.headers.get('Expires')).getTime() - requestTime;\n if (timeUntilExpiry < MIN_TIME_UNTIL_EXPIRY) return;\n\n prepareBody(response, body => {\n const clonedResponse = new window.Response(body, options);\n\n window.caches.open(CACHE_NAME)\n .then(cache => cache.put(stripQueryParameters(request.url), clonedResponse))\n .catch(e => warnOnce(e.message));\n });\n}\n\nfunction stripQueryParameters(url: string) {\n const start = url.indexOf('?');\n return start < 0 ? url : url.slice(0, start);\n}\n\nexport function cacheGet(request: Request, callback: (error: ?any, response: ?Response, fresh: ?boolean) => void) {\n if (!window.caches) return callback(null);\n\n const strippedURL = stripQueryParameters(request.url);\n\n window.caches.open(CACHE_NAME)\n .then(cache => {\n // manually strip URL instead of `ignoreSearch: true` because of a known\n // performance issue in Chrome https://github.com/mapbox/mapbox-gl-js/issues/8431\n cache.match(strippedURL)\n .then(response => {\n const fresh = isFresh(response);\n\n // Reinsert into cache so that order of keys in the cache is the order of access.\n // This line makes the cache a LRU instead of a FIFO cache.\n cache.delete(strippedURL);\n if (fresh) {\n cache.put(strippedURL, response.clone());\n }\n\n callback(null, response, fresh);\n })\n .catch(callback);\n })\n .catch(callback);\n\n}\n\nfunction isFresh(response) {\n if (!response) return false;\n const expires = new Date(response.headers.get('Expires'));\n const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || '');\n return expires > Date.now() && !cacheControl['no-cache'];\n}\n\n// `Infinity` triggers a cache check after the first tile is loaded\n// so that a check is run at least once on each page load.\nlet globalEntryCounter = Infinity;\n\n// The cache check gets run on a worker. The reason for this is that\n// profiling sometimes shows this as taking up significant time on the\n// thread it gets called from. And sometimes it doesn't. It *may* be\n// fine to run this on the main thread but out of caution this is being\n// dispatched on a worker. This can be investigated further in the future.\nexport function cacheEntryPossiblyAdded(dispatcher: Dispatcher) {\n globalEntryCounter++;\n if (globalEntryCounter > cacheCheckThreshold) {\n dispatcher.getActor().send('enforceCacheSizeLimit', cacheLimit);\n globalEntryCounter = 0;\n }\n}\n\n// runs on worker, see above comment\nexport function enforceCacheSizeLimit(limit: number) {\n if (!window.caches) return;\n window.caches.open(CACHE_NAME)\n .then(cache => {\n cache.keys().then(keys => {\n for (let i = 0; i < keys.length - limit; i++) {\n cache.delete(keys[i]);\n }\n });\n });\n}\n\nexport function clearTileCache(callback?: (err: ?Error) => void) {\n const promise = window.caches.delete(CACHE_NAME);\n if (callback) {\n promise.catch(callback).then(() => callback());\n }\n}\n\nexport function setCacheLimits(limit: number, checkThreshold: number) {\n cacheLimit = limit;\n cacheCheckThreshold = checkThreshold;\n}\n","// @flow\n\nimport window from './window';\nimport { extend, warnOnce } from './util';\nimport { isMapboxHTTPURL, hasCacheDefeatingSku } from './mapbox';\nimport config from './config';\nimport assert from 'assert';\nimport { cacheGet, cachePut } from './tile_request_cache';\n\nimport type { Callback } from '../types/callback';\nimport type { Cancelable } from '../types/cancelable';\n\n/**\n * The type of a resource.\n * @private\n * @readonly\n * @enum {string}\n */\nconst ResourceType = {\n Unknown: 'Unknown',\n Style: 'Style',\n Source: 'Source',\n Tile: 'Tile',\n Glyphs: 'Glyphs',\n SpriteImage: 'SpriteImage',\n SpriteJSON: 'SpriteJSON',\n Image: 'Image'\n};\nexport { ResourceType };\n\nif (typeof Object.freeze == 'function') {\n Object.freeze(ResourceType);\n}\n\n/**\n * A `RequestParameters` object to be returned from Map.options.transformRequest callbacks.\n * @typedef {Object} RequestParameters\n * @property {string} url The URL to be requested.\n * @property {Object} headers The headers to be sent with the request.\n * @property {string} credentials `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests.\n */\nexport type RequestParameters = {\n url: string,\n headers?: Object,\n method?: 'GET' | 'POST' | 'PUT',\n body?: string,\n type?: 'string' | 'json' | 'arrayBuffer',\n credentials?: 'same-origin' | 'include',\n collectResourceTiming?: boolean\n};\n\nexport type ResponseCallback = (error: ?Error, data: ?T, cacheControl: ?string, expires: ?string) => void;\n\nclass AJAXError extends Error {\n status: number;\n url: string;\n constructor(message: string, status: number, url: string) {\n if (status === 401 && isMapboxHTTPURL(url)) {\n message += ': you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes';\n }\n super(message);\n this.status = status;\n this.url = url;\n\n // work around for https://github.com/Rich-Harris/buble/issues/40\n this.name = this.constructor.name;\n this.message = message;\n }\n\n toString() {\n return `${this.name}: ${this.message} (${this.status}): ${this.url}`;\n }\n}\n\nfunction isWorker() {\n return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope;\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, IE),\n// and we will set an empty referrer. Otherwise, we're using the document's URL.\n/* global self, WorkerGlobalScope */\nexport const getReferrer = isWorker() ?\n () => self.worker && self.worker.referrer :\n () => (window.location.protocol === 'blob:' ? window.parent : window).location.href;\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.\nconst isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\\w+:/.test(url));\n\nfunction makeFetchRequest(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable {\n const controller = new window.AbortController();\n const request = new window.Request(requestParameters.url, {\n method: requestParameters.method || 'GET',\n body: requestParameters.body,\n credentials: requestParameters.credentials,\n headers: requestParameters.headers,\n referrer: getReferrer(),\n signal: controller.signal\n });\n let complete = false;\n let aborted = false;\n\n const cacheIgnoringSearch = hasCacheDefeatingSku(request.url);\n\n if (requestParameters.type === 'json') {\n request.headers.set('Accept', 'application/json');\n }\n\n const validateOrFetch = (err, cachedResponse, responseIsFresh) => {\n if (aborted) return;\n\n if (err) {\n // Do fetch in case of cache error.\n // HTTP pages in Edge trigger a security error that can be ignored.\n if (err.message !== 'SecurityError') {\n warnOnce(err);\n }\n }\n\n if (cachedResponse && responseIsFresh) {\n return finishRequest(cachedResponse);\n }\n\n if (cachedResponse) {\n // We can't do revalidation with 'If-None-Match' because then the\n // request doesn't have simple cors headers.\n }\n\n const requestTime = Date.now();\n\n window.fetch(request).then(response => {\n if (response.ok) {\n const cacheableResponse = cacheIgnoringSearch ? response.clone() : null;\n return finishRequest(response, cacheableResponse, requestTime);\n\n } else {\n return callback(new AJAXError(response.statusText, response.status, requestParameters.url));\n }\n }).catch(error => {\n if (error.code === 20) {\n // silence expected AbortError\n return;\n }\n callback(new Error(error.message));\n });\n };\n\n const finishRequest = (response, cacheableResponse, requestTime) => {\n (\n requestParameters.type === 'arrayBuffer' ? response.arrayBuffer() :\n requestParameters.type === 'json' ? response.json() :\n response.text()\n ).then(result => {\n if (aborted) return;\n if (cacheableResponse && requestTime) {\n // The response needs to be inserted into the cache after it has completely loaded.\n // Until it is fully loaded there is a chance it will be aborted. Aborting while\n // reading the body can cause the cache insertion to error. We could catch this error\n // in most browsers but in Firefox it seems to sometimes crash the tab. Adding\n // it to the cache here avoids that error.\n cachePut(request, cacheableResponse, requestTime);\n }\n complete = true;\n callback(null, result, response.headers.get('Cache-Control'), response.headers.get('Expires'));\n }).catch(err => callback(new Error(err.message)));\n };\n\n if (cacheIgnoringSearch) {\n cacheGet(request, validateOrFetch);\n } else {\n validateOrFetch(null, null);\n }\n\n return { cancel: () => {\n aborted = true;\n if (!complete) controller.abort();\n }};\n}\n\nfunction makeXMLHttpRequest(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable {\n const xhr: XMLHttpRequest = new window.XMLHttpRequest();\n\n xhr.open(requestParameters.method || 'GET', requestParameters.url, true);\n if (requestParameters.type === 'arrayBuffer') {\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 xhr.setRequestHeader('Accept', 'application/json');\n }\n xhr.withCredentials = requestParameters.credentials === 'include';\n xhr.onerror = () => {\n callback(new Error(xhr.statusText));\n };\n xhr.onload = () => {\n if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) {\n let data: mixed = 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 return callback(err);\n }\n }\n callback(null, data, xhr.getResponseHeader('Cache-Control'), xhr.getResponseHeader('Expires'));\n } else {\n callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url));\n }\n };\n xhr.send(requestParameters.body);\n return { cancel: () => xhr.abort() };\n}\n\nexport const makeRequest = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable {\n // We're trying to use the Fetch API if possible. However, in some situations we can't use it:\n // - IE11 doesn't support it at all. In this case, we dispatch the request to the main thread so\n // that we can get an accruate referrer header.\n // - Safari exposes window.AbortController, but it doesn't work actually abort any requests in\n // some versions (see https://bugs.webkit.org/show_bug.cgi?id=174980#c2)\n // - Requests for resources with the file:// URI scheme don't work with the Fetch API either. In\n // this case we unconditionally use XHR on the current thread since referrers don't matter.\n if (!isFileURL(requestParameters.url)) {\n if (window.fetch && window.Request && window.AbortController && window.Request.prototype.hasOwnProperty('signal')) {\n return makeFetchRequest(requestParameters, callback);\n }\n if (isWorker() && self.worker && self.worker.actor) {\n return self.worker.actor.send('getResource', requestParameters, callback);\n }\n }\n return makeXMLHttpRequest(requestParameters, callback);\n};\n\nexport const getJSON = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable {\n return makeRequest(extend(requestParameters, { type: 'json' }), callback);\n};\n\nexport const getArrayBuffer = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable {\n return makeRequest(extend(requestParameters, { type: 'arrayBuffer' }), callback);\n};\n\nexport const postData = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable {\n return makeRequest(extend(requestParameters, { method: 'POST' }), callback);\n};\n\nfunction sameOrigin(url) {\n const a: HTMLAnchorElement = window.document.createElement('a');\n a.href = url;\n return a.protocol === window.document.location.protocol && a.host === window.document.location.host;\n}\n\nconst transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=';\n\nlet imageQueue, numImageRequests;\nexport const resetImageRequestQueue = () => {\n imageQueue = [];\n numImageRequests = 0;\n};\nresetImageRequestQueue();\n\nexport const getImage = function(requestParameters: RequestParameters, callback: Callback): Cancelable {\n // limit concurrent image loads to help with raster sources performance on big screens\n if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) {\n const queued = {\n requestParameters,\n callback,\n cancelled: false,\n cancel() { this.cancelled = true; }\n };\n imageQueue.push(queued);\n return queued;\n }\n numImageRequests++;\n\n let advanced = false;\n const advanceImageRequestQueue = () => {\n if (advanced) return;\n advanced = true;\n numImageRequests--;\n assert(numImageRequests >= 0);\n while (imageQueue.length && numImageRequests < config.MAX_PARALLEL_IMAGE_REQUESTS) { // eslint-disable-line\n const request = imageQueue.shift();\n const {requestParameters, callback, cancelled} = request;\n if (!cancelled) {\n request.cancel = getImage(requestParameters, callback).cancel;\n }\n }\n };\n\n // request the image with XHR to work around caching issues\n // see https://github.com/mapbox/mapbox-gl-js/issues/1470\n const request = getArrayBuffer(requestParameters, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => {\n\n advanceImageRequestQueue();\n\n if (err) {\n callback(err);\n } else if (data) {\n const img: HTMLImageElement = new window.Image();\n const URL = window.URL || window.webkitURL;\n img.onload = () => {\n callback(null, img);\n URL.revokeObjectURL(img.src);\n };\n img.onerror = () => callback(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 window.Blob([new Uint8Array(data)], { type: 'image/png' });\n (img: any).cacheControl = cacheControl;\n (img: any).expires = expires;\n img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl;\n }\n });\n\n return {\n cancel: () => {\n request.cancel();\n advanceImageRequestQueue();\n }\n };\n};\n\nexport const getVideo = function(urls: Array, callback: Callback): Cancelable {\n const video: HTMLVideoElement = window.document.createElement('video');\n video.muted = true;\n video.onloadstart = function() {\n callback(null, video);\n };\n for (let i = 0; i < urls.length; i++) {\n const s: HTMLSourceElement = window.document.createElement('source');\n if (!sameOrigin(urls[i])) {\n video.crossOrigin = 'Anonymous';\n }\n s.src = urls[i];\n video.appendChild(s);\n }\n return { cancel: () => {} };\n};\n","// @flow\n\nimport { extend } from './util';\n\ntype Listener = (Object) => any;\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\nexport class Event {\n +type: string;\n\n constructor(type: string, data: Object = {}) {\n extend(this, data);\n this.type = type;\n }\n}\n\nexport class ErrorEvent extends Event {\n error: Error;\n\n constructor(error: Error, data: Object = {}) {\n super('error', extend({error}, data));\n }\n}\n\n/**\n * Methods mixed in to other classes for event capabilities.\n *\n * @mixin Evented\n */\nexport class Evented {\n _listeners: Listeners;\n _oneTimeListeners: Listeners;\n _eventedParent: ?Evented;\n _eventedParentData: ?(Object | () => Object);\n\n /**\n * Adds a listener to a specified event type.\n *\n * @param {string} type The event type to add a listen for.\n * @param {Function} 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 * @returns {Object} `this`\n */\n on(type: *, 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 {string} type The event type to remove listeners for.\n * @param {Function} listener The listener function to remove.\n * @returns {Object} `this`\n */\n off(type: *, 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 {string} type The event type to listen for.\n * @param {Function} listener The function to be called when the event is fired the first time.\n * @returns {Object} `this`\n */\n once(type: string, listener: Listener) {\n this._oneTimeListeners = this._oneTimeListeners || {};\n _addEventListener(type, listener, this._oneTimeListeners);\n\n return this;\n }\n\n fire(event: Event, properties?: Object) {\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: 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 {string} type The event type\n * @returns {boolean} `true` if there is at least one registered listener for specified event type, `false` otherwise\n * @private\n */\n listens(type: string) {\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 * @private\n * @returns {Object} `this`\n * @private\n */\n setEventedParent(parent: ?Evented, data?: Object | () => Object) {\n this._eventedParent = parent;\n this._eventedParentData = data;\n\n return this;\n }\n}\n","\nexport default class ValidationError {\n constructor(key, value, message, identifier) {\n this.message = (key ? `${key}: ` : '') + message;\n if (identifier) this.identifier = identifier;\n\n if (value !== null && value !== undefined && value.__line__) {\n this.line = value.__line__;\n }\n }\n}\n","\nimport ValidationError from '../error/validation_error';\n\nexport default function validateConstants(options) {\n const key = options.key;\n const constants = options.value;\n\n if (constants) {\n return [new ValidationError(key, constants, 'constants have been deprecated as of v8')];\n } else {\n return [];\n }\n}\n","\nexport default function (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","function isPrimitive(value) {\n return value instanceof Number || value instanceof String || value instanceof Boolean;\n}\n\n// Turn jsonlint-lines-primitives objects into primitive objects\nexport function unbundle(value) {\n if (isPrimitive(value)) {\n return value.valueOf();\n } else {\n return value;\n }\n}\n\nexport function deepUnbundle(value) {\n if (Array.isArray(value)) {\n return value.map(deepUnbundle);\n } else if (value instanceof Object && !isPrimitive(value)) {\n const unbundledValue = {};\n for (const key in value) {\n unbundledValue[key] = deepUnbundle(value[key]);\n }\n return unbundledValue;\n }\n\n return unbundle(value);\n}\n\n","// @flow\n\nclass ParsingError extends Error {\n key: string;\n message: string;\n constructor(key: string, message: string) {\n super(message);\n this.message = message;\n this.key = key;\n }\n}\n\nexport default ParsingError;\n","// @flow\n\nimport type {Expression} from './expression';\n\n/**\n * Tracks `let` bindings during expression parsing.\n * @private\n */\nclass Scope {\n parent: ?Scope;\n bindings: {[string]: Expression};\n constructor(parent?: Scope, bindings: Array<[string, Expression]> = []) {\n this.parent = parent;\n this.bindings = {};\n for (const [name, expression] of bindings) {\n this.bindings[name] = expression;\n }\n }\n\n concat(bindings: Array<[string, Expression]>) {\n return new Scope(this, bindings);\n }\n\n get(name: string): Expression {\n if (this.bindings[name]) { return this.bindings[name]; }\n if (this.parent) { return this.parent.get(name); }\n throw new Error(`${name} not found in scope.`);\n }\n\n has(name: string): boolean {\n if (this.bindings[name]) return true;\n return this.parent ? this.parent.has(name) : false;\n }\n}\n\nexport default Scope;\n","// @flow\n\nexport type NullTypeT = { kind: 'null' };\nexport type NumberTypeT = { kind: 'number' };\nexport type StringTypeT = { kind: 'string' };\nexport type BooleanTypeT = { kind: 'boolean' };\nexport type ColorTypeT = { kind: 'color' };\nexport type ObjectTypeT = { kind: 'object' };\nexport type ValueTypeT = { kind: 'value' };\nexport type ErrorTypeT = { kind: 'error' };\nexport type CollatorTypeT = { kind: 'collator' };\nexport type FormattedTypeT = { kind: 'formatted' };\n\nexport type EvaluationKind = 'constant' | 'source' | 'camera' | 'composite';\n\nexport type Type =\n NullTypeT |\n NumberTypeT |\n StringTypeT |\n BooleanTypeT |\n ColorTypeT |\n ObjectTypeT |\n ValueTypeT |\n ArrayType | // eslint-disable-line no-use-before-define\n ErrorTypeT |\n CollatorTypeT |\n FormattedTypeT\n\nexport type ArrayType = {\n kind: 'array',\n itemType: Type,\n N: ?number\n}\n\nexport const NullType = { kind: 'null' };\nexport const NumberType = { kind: 'number' };\nexport const StringType = { kind: 'string' };\nexport const BooleanType = { kind: 'boolean' };\nexport const ColorType = { kind: 'color' };\nexport const ObjectType = { kind: 'object' };\nexport const ValueType = { kind: 'value' };\nexport const ErrorType = { kind: 'error' };\nexport const CollatorType = { kind: 'collator' };\nexport const FormattedType = { kind: 'formatted' };\n\nexport function array(itemType: Type, N: ?number): ArrayType {\n return {\n kind: 'array',\n itemType,\n N\n };\n}\n\nexport function toString(type: Type): string {\n if (type.kind === 'array') {\n const itemType = toString(type.itemType);\n return typeof type.N === 'number' ?\n `array<${itemType}, ${type.N}>` :\n type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`;\n } else {\n return type.kind;\n }\n}\n\nconst valueMemberTypes = [\n NullType,\n NumberType,\n StringType,\n BooleanType,\n ColorType,\n FormattedType,\n ObjectType,\n array(ValueType)\n];\n\n/**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message.\n * @private\n */\nexport function checkSubtype(expected: Type, t: Type): ?string {\n if (t.kind === 'error') {\n // Error is a subtype of every type\n return null;\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 } else if (expected.kind === t.kind) {\n return null;\n } else if (expected.kind === 'value') {\n for (const memberType of valueMemberTypes) {\n if (!checkSubtype(memberType, t)) {\n return null;\n }\n }\n }\n\n return `Expected ${toString(expected)} but found ${toString(t)} instead.`;\n}\n","// (c) Dean McNamee , 2012.\n//\n// https://github.com/deanm/css-color-parser-js\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n// http://www.w3.org/TR/css3-color/\nvar kCSSColorTable = {\n \"transparent\": [0,0,0,0], \"aliceblue\": [240,248,255,1],\n \"antiquewhite\": [250,235,215,1], \"aqua\": [0,255,255,1],\n \"aquamarine\": [127,255,212,1], \"azure\": [240,255,255,1],\n \"beige\": [245,245,220,1], \"bisque\": [255,228,196,1],\n \"black\": [0,0,0,1], \"blanchedalmond\": [255,235,205,1],\n \"blue\": [0,0,255,1], \"blueviolet\": [138,43,226,1],\n \"brown\": [165,42,42,1], \"burlywood\": [222,184,135,1],\n \"cadetblue\": [95,158,160,1], \"chartreuse\": [127,255,0,1],\n \"chocolate\": [210,105,30,1], \"coral\": [255,127,80,1],\n \"cornflowerblue\": [100,149,237,1], \"cornsilk\": [255,248,220,1],\n \"crimson\": [220,20,60,1], \"cyan\": [0,255,255,1],\n \"darkblue\": [0,0,139,1], \"darkcyan\": [0,139,139,1],\n \"darkgoldenrod\": [184,134,11,1], \"darkgray\": [169,169,169,1],\n \"darkgreen\": [0,100,0,1], \"darkgrey\": [169,169,169,1],\n \"darkkhaki\": [189,183,107,1], \"darkmagenta\": [139,0,139,1],\n \"darkolivegreen\": [85,107,47,1], \"darkorange\": [255,140,0,1],\n \"darkorchid\": [153,50,204,1], \"darkred\": [139,0,0,1],\n \"darksalmon\": [233,150,122,1], \"darkseagreen\": [143,188,143,1],\n \"darkslateblue\": [72,61,139,1], \"darkslategray\": [47,79,79,1],\n \"darkslategrey\": [47,79,79,1], \"darkturquoise\": [0,206,209,1],\n \"darkviolet\": [148,0,211,1], \"deeppink\": [255,20,147,1],\n \"deepskyblue\": [0,191,255,1], \"dimgray\": [105,105,105,1],\n \"dimgrey\": [105,105,105,1], \"dodgerblue\": [30,144,255,1],\n \"firebrick\": [178,34,34,1], \"floralwhite\": [255,250,240,1],\n \"forestgreen\": [34,139,34,1], \"fuchsia\": [255,0,255,1],\n \"gainsboro\": [220,220,220,1], \"ghostwhite\": [248,248,255,1],\n \"gold\": [255,215,0,1], \"goldenrod\": [218,165,32,1],\n \"gray\": [128,128,128,1], \"green\": [0,128,0,1],\n \"greenyellow\": [173,255,47,1], \"grey\": [128,128,128,1],\n \"honeydew\": [240,255,240,1], \"hotpink\": [255,105,180,1],\n \"indianred\": [205,92,92,1], \"indigo\": [75,0,130,1],\n \"ivory\": [255,255,240,1], \"khaki\": [240,230,140,1],\n \"lavender\": [230,230,250,1], \"lavenderblush\": [255,240,245,1],\n \"lawngreen\": [124,252,0,1], \"lemonchiffon\": [255,250,205,1],\n \"lightblue\": [173,216,230,1], \"lightcoral\": [240,128,128,1],\n \"lightcyan\": [224,255,255,1], \"lightgoldenrodyellow\": [250,250,210,1],\n \"lightgray\": [211,211,211,1], \"lightgreen\": [144,238,144,1],\n \"lightgrey\": [211,211,211,1], \"lightpink\": [255,182,193,1],\n \"lightsalmon\": [255,160,122,1], \"lightseagreen\": [32,178,170,1],\n \"lightskyblue\": [135,206,250,1], \"lightslategray\": [119,136,153,1],\n \"lightslategrey\": [119,136,153,1], \"lightsteelblue\": [176,196,222,1],\n \"lightyellow\": [255,255,224,1], \"lime\": [0,255,0,1],\n \"limegreen\": [50,205,50,1], \"linen\": [250,240,230,1],\n \"magenta\": [255,0,255,1], \"maroon\": [128,0,0,1],\n \"mediumaquamarine\": [102,205,170,1], \"mediumblue\": [0,0,205,1],\n \"mediumorchid\": [186,85,211,1], \"mediumpurple\": [147,112,219,1],\n \"mediumseagreen\": [60,179,113,1], \"mediumslateblue\": [123,104,238,1],\n \"mediumspringgreen\": [0,250,154,1], \"mediumturquoise\": [72,209,204,1],\n \"mediumvioletred\": [199,21,133,1], \"midnightblue\": [25,25,112,1],\n \"mintcream\": [245,255,250,1], \"mistyrose\": [255,228,225,1],\n \"moccasin\": [255,228,181,1], \"navajowhite\": [255,222,173,1],\n \"navy\": [0,0,128,1], \"oldlace\": [253,245,230,1],\n \"olive\": [128,128,0,1], \"olivedrab\": [107,142,35,1],\n \"orange\": [255,165,0,1], \"orangered\": [255,69,0,1],\n \"orchid\": [218,112,214,1], \"palegoldenrod\": [238,232,170,1],\n \"palegreen\": [152,251,152,1], \"paleturquoise\": [175,238,238,1],\n \"palevioletred\": [219,112,147,1], \"papayawhip\": [255,239,213,1],\n \"peachpuff\": [255,218,185,1], \"peru\": [205,133,63,1],\n \"pink\": [255,192,203,1], \"plum\": [221,160,221,1],\n \"powderblue\": [176,224,230,1], \"purple\": [128,0,128,1],\n \"rebeccapurple\": [102,51,153,1],\n \"red\": [255,0,0,1], \"rosybrown\": [188,143,143,1],\n \"royalblue\": [65,105,225,1], \"saddlebrown\": [139,69,19,1],\n \"salmon\": [250,128,114,1], \"sandybrown\": [244,164,96,1],\n \"seagreen\": [46,139,87,1], \"seashell\": [255,245,238,1],\n \"sienna\": [160,82,45,1], \"silver\": [192,192,192,1],\n \"skyblue\": [135,206,235,1], \"slateblue\": [106,90,205,1],\n \"slategray\": [112,128,144,1], \"slategrey\": [112,128,144,1],\n \"snow\": [255,250,250,1], \"springgreen\": [0,255,127,1],\n \"steelblue\": [70,130,180,1], \"tan\": [210,180,140,1],\n \"teal\": [0,128,128,1], \"thistle\": [216,191,216,1],\n \"tomato\": [255,99,71,1], \"turquoise\": [64,224,208,1],\n \"violet\": [238,130,238,1], \"wheat\": [245,222,179,1],\n \"white\": [255,255,255,1], \"whitesmoke\": [245,245,245,1],\n \"yellow\": [255,255,0,1], \"yellowgreen\": [154,205,50,1]}\n\nfunction clamp_css_byte(i) { // Clamp to integer 0 .. 255.\n i = Math.round(i); // Seems to be what Chrome does (vs truncation).\n return i < 0 ? 0 : i > 255 ? 255 : i;\n}\n\nfunction clamp_css_float(f) { // Clamp to float 0.0 .. 1.0.\n return f < 0 ? 0 : f > 1 ? 1 : f;\n}\n\nfunction parse_css_int(str) { // int or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_byte(parseFloat(str) / 100 * 255);\n return clamp_css_byte(parseInt(str));\n}\n\nfunction parse_css_float(str) { // float or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_float(parseFloat(str) / 100);\n return clamp_css_float(parseFloat(str));\n}\n\nfunction css_hue_to_rgb(m1, m2, h) {\n if (h < 0) h += 1;\n else if (h > 1) h -= 1;\n\n if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;\n if (h * 2 < 1) return m2;\n if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;\n return m1;\n}\n\nfunction parseCSSColor(css_str) {\n // Remove all whitespace, not compliant, but should just be more accepting.\n var str = css_str.replace(/ /g, '').toLowerCase();\n\n // Color keywords (and transparent) lookup.\n if (str in kCSSColorTable) return kCSSColorTable[str].slice(); // dup.\n\n // #abc and #abc123 syntax.\n if (str[0] === '#') {\n if (str.length === 4) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xfff)) return null; // Covers NaN.\n return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),\n (iv & 0xf0) | ((iv & 0xf0) >> 4),\n (iv & 0xf) | ((iv & 0xf) << 4),\n 1];\n } else if (str.length === 7) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN.\n return [(iv & 0xff0000) >> 16,\n (iv & 0xff00) >> 8,\n iv & 0xff,\n 1];\n }\n\n return null;\n }\n\n var op = str.indexOf('('), ep = str.indexOf(')');\n if (op !== -1 && ep + 1 === str.length) {\n var fname = str.substr(0, op);\n var params = str.substr(op+1, ep-(op+1)).split(',');\n var alpha = 1; // To allow case fallthrough.\n switch (fname) {\n case 'rgba':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'rgb':\n if (params.length !== 3) return null;\n return [parse_css_int(params[0]),\n parse_css_int(params[1]),\n parse_css_int(params[2]),\n alpha];\n case 'hsla':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'hsl':\n if (params.length !== 3) return null;\n var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1\n // NOTE(deanm): According to the CSS spec s/l should only be\n // percentages, but we don't bother and let float or percentage.\n var s = parse_css_float(params[1]);\n var l = parse_css_float(params[2]);\n var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;\n var m1 = l * 2 - m2;\n return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255),\n alpha];\n default:\n return null;\n }\n }\n\n return null;\n}\n\ntry { exports.parseCSSColor = parseCSSColor } catch(e) { }\n","// @flow\n\nimport { parseCSSColor } from 'csscolorparser';\n\n/**\n * An RGBA color value. Create instances from color strings using the static\n * method `Color.parse`. The constructor accepts RGB channel values in the range\n * `[0, 1]`, premultiplied by A.\n *\n * @param {number} r The red channel.\n * @param {number} g The green channel.\n * @param {number} b The blue channel.\n * @param {number} a The alpha channel.\n * @private\n */\nclass Color {\n r: number;\n g: number;\n b: number;\n a: number;\n\n constructor(r: number, g: number, b: number, a: number = 1) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n\n static black: Color;\n static white: Color;\n static transparent: Color;\n static red: Color;\n\n /**\n * Parses valid CSS color strings and returns a `Color` instance.\n * @returns A `Color` instance, or `undefined` if the input is not a valid color string.\n */\n static parse(input: ?string): Color | void {\n if (!input) {\n return undefined;\n }\n\n if (input instanceof Color) {\n return input;\n }\n\n if (typeof input !== 'string') {\n return undefined;\n }\n\n const rgba = parseCSSColor(input);\n if (!rgba) {\n return undefined;\n }\n\n return new Color(\n rgba[0] / 255 * rgba[3],\n rgba[1] / 255 * rgba[3],\n rgba[2] / 255 * rgba[3],\n rgba[3]\n );\n }\n\n /**\n * Returns an RGBA string representing the color value.\n *\n * @returns An RGBA string.\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(): string {\n const [r, g, b, a] = this.toArray();\n return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`;\n }\n\n toArray(): [number, number, number, number] {\n const {r, g, b, a} = this;\n return a === 0 ? [0, 0, 0, 0] : [\n r * 255 / a,\n g * 255 / a,\n b * 255 / a,\n a\n ];\n }\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\nexport default Color;\n","// @flow\n\n// Flow type declarations for Intl cribbed from\n// https://github.com/facebook/flow/issues/1270\n\ndeclare var Intl: {\n Collator: Class\n};\n\ndeclare class Intl$Collator {\n constructor (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n static (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n compare (a: string, b: string): number;\n\n resolvedOptions(): any;\n}\n\ntype CollatorOptions = {\n localeMatcher?: 'lookup' | 'best fit',\n usage?: 'sort' | 'search',\n sensitivity?: 'base' | 'accent' | 'case' | 'variant',\n ignorePunctuation?: boolean,\n numeric?: boolean,\n caseFirst?: 'upper' | 'lower' | 'false'\n}\n\nexport default class Collator {\n locale: string | null;\n sensitivity: 'base' | 'accent' | 'case' | 'variant';\n collator: Intl$Collator;\n\n constructor(caseSensitive: boolean, diacriticSensitive: boolean, locale: string | null) {\n if (caseSensitive)\n this.sensitivity = diacriticSensitive ? 'variant' : 'case';\n else\n this.sensitivity = diacriticSensitive ? 'accent' : 'base';\n\n this.locale = locale;\n this.collator = new Intl.Collator(this.locale ? this.locale : [],\n { sensitivity: this.sensitivity, usage: 'search' });\n }\n\n compare(lhs: string, rhs: string): number {\n return this.collator.compare(lhs, rhs);\n }\n\n resolvedLocale(): string {\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","// @flow\n\nimport type Color from '../../util/color';\n\nexport class FormattedSection {\n text: string;\n scale: number | null;\n fontStack: string | null;\n textColor: Color | null;\n\n constructor(text: string, scale: number | null, fontStack: string | null, textColor: Color | null) {\n this.text = text;\n this.scale = scale;\n this.fontStack = fontStack;\n this.textColor = textColor;\n }\n}\n\nexport default class Formatted {\n sections: Array;\n\n constructor(sections: Array) {\n this.sections = sections;\n }\n\n static fromString(unformatted: string): Formatted {\n return new Formatted([new FormattedSection(unformatted, null, null, null)]);\n }\n\n toString(): string {\n return this.sections.map(section => section.text).join('');\n }\n\n serialize(): Array {\n const serialized = [\"format\"];\n for (const section of this.sections) {\n serialized.push(section.text);\n const options = {};\n if (section.fontStack) {\n options[\"text-font\"] = [\"literal\", section.fontStack.split(',')];\n }\n if (section.scale) {\n options[\"font-scale\"] = section.scale;\n }\n if (section.textColor) {\n options[\"text-color\"] = [\"rgba\"].concat(section.textColor.toArray());\n }\n serialized.push(options);\n }\n return serialized;\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport Color from '../util/color';\nimport Collator from './types/collator';\nimport Formatted from './types/formatted';\nimport { NullType, NumberType, StringType, BooleanType, ColorType, ObjectType, ValueType, CollatorType, FormattedType, array } from './types';\n\nimport type { Type } from './types';\n\nexport function validateRGBA(r: mixed, g: mixed, b: mixed, a?: mixed): ?string {\n if (!(\n typeof r === 'number' && r >= 0 && r <= 255 &&\n typeof g === 'number' && g >= 0 && g <= 255 &&\n typeof b === 'number' && b >= 0 && b <= 255\n )) {\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\n if (!(\n typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1)\n )) {\n return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`;\n }\n\n return null;\n}\n\nexport type Value = null | string | boolean | number | Color | Collator | Formatted | $ReadOnlyArray | { +[string]: Value }\n\nexport function isValue(mixed: mixed): boolean {\n if (mixed === null) {\n return true;\n } else if (typeof mixed === 'string') {\n return true;\n } else if (typeof mixed === 'boolean') {\n return true;\n } else if (typeof mixed === 'number') {\n return true;\n } else if (mixed instanceof Color) {\n return true;\n } else if (mixed instanceof Collator) {\n return true;\n } else if (mixed instanceof Formatted) {\n return true;\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 } 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 } else {\n return false;\n }\n}\n\nexport function typeOf(value: Value): Type {\n if (value === null) {\n return NullType;\n } else if (typeof value === 'string') {\n return StringType;\n } else if (typeof value === 'boolean') {\n return BooleanType;\n } else if (typeof value === 'number') {\n return NumberType;\n } else if (value instanceof Color) {\n return ColorType;\n } else if (value instanceof Collator) {\n return CollatorType;\n } else if (value instanceof Formatted) {\n return FormattedType;\n } else if (Array.isArray(value)) {\n const length = value.length;\n let itemType: ?Type;\n\n for (const item of value) {\n const t = typeOf(item);\n if (!itemType) {\n itemType = t;\n } else if (itemType === t) {\n continue;\n } else {\n itemType = ValueType;\n break;\n }\n }\n\n return array(itemType || ValueType, length);\n } else {\n assert(typeof value === 'object');\n return ObjectType;\n }\n}\n\nexport function toString(value: Value) {\n const type = typeof value;\n if (value === null) {\n return '';\n } else if (type === 'string' || type === 'number' || type === 'boolean') {\n return String(value);\n } else if (value instanceof Color || value instanceof Formatted) {\n return value.toString();\n } else {\n return JSON.stringify(value);\n }\n}\n\nexport { Color, Collator };\n","// @flow\n\nimport assert from 'assert';\nimport { isValue, typeOf, Color } from '../values';\nimport Formatted from '../types/formatted';\n\nimport type { Type } from '../types';\nimport type { Value } from '../values';\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\n\nclass Literal implements Expression {\n type: Type;\n value: Value;\n\n constructor(type: Type, value: Value) {\n this.type = type;\n this.value = value;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2)\n return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n\n if (!isValue(args[1]))\n return context.error(`invalid value`);\n\n const value = (args[1]: any);\n let type = typeOf(value);\n\n // special case: infer the item type if possible for zero-length arrays\n const expected = context.expectedType;\n if (\n type.kind === 'array' &&\n type.N === 0 &&\n expected &&\n expected.kind === 'array' &&\n (typeof expected.N !== 'number' || expected.N === 0)\n ) {\n type = expected;\n }\n\n return new Literal(type, value);\n }\n\n evaluate() {\n return this.value;\n }\n\n eachChild() {}\n\n possibleOutputs() {\n return [this.value];\n }\n\n serialize(): Array {\n if (this.type.kind === 'array' || this.type.kind === 'object') {\n return [\"literal\", this.value];\n } else if (this.value instanceof Color) {\n // Constant-folding can generate Literal expressions that you\n // couldn't actually generate with a \"literal\" expression,\n // so we have to implement an equivalent serialization here\n return [\"rgba\"].concat(this.value.toArray());\n } else if (this.value instanceof Formatted) {\n // Same as Color\n return this.value.serialize();\n } else {\n assert(this.value === null ||\n typeof this.value === 'string' ||\n typeof this.value === 'number' ||\n typeof this.value === 'boolean');\n return (this.value: any);\n }\n }\n}\n\nexport default Literal;\n","// @flow\n\nclass RuntimeError {\n name: string;\n message: string;\n\n constructor(message: string) {\n this.name = 'ExpressionEvaluationError';\n this.message = message;\n }\n\n toJSON() {\n return this.message;\n }\n}\n\nexport default RuntimeError;\n","// @flow\n\nimport assert from 'assert';\n\nimport {\n ObjectType,\n ValueType,\n StringType,\n NumberType,\n BooleanType,\n checkSubtype,\n toString,\n array\n} from '../types';\nimport RuntimeError from '../runtime_error';\nimport { typeOf } from '../values';\n\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Value } from '../values';\nimport type { Type } from '../types';\n\nconst types = {\n string: StringType,\n number: NumberType,\n boolean: BooleanType,\n object: ObjectType\n};\n\nclass Assertion implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n let i = 1;\n let type;\n\n const name: string = (args[0]: any);\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) || type === 'object')\n return context.error('The item type argument of \"array\" must be one of string, number, boolean', 1);\n itemType = types[type];\n i++;\n } else {\n itemType = ValueType;\n }\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 ) {\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\n type = array(itemType, N);\n } else {\n assert(types[name], name);\n type = types[name];\n }\n\n const parsed = [];\n for (; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input) return null;\n parsed.push(input);\n }\n\n return new Assertion(type, parsed);\n }\n\n evaluate(ctx: EvaluationContext) {\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 } else if (i === this.args.length - 1) {\n throw new RuntimeError(`Expected value to be of type ${toString(this.type)}, but found ${toString(typeOf(value))} instead.`);\n }\n }\n\n assert(false);\n return null;\n }\n\n eachChild(fn: (Expression) => void) {\n this.args.forEach(fn);\n }\n\n possibleOutputs(): Array {\n return [].concat(...this.args.map((arg) => arg.possibleOutputs()));\n }\n\n serialize(): Array {\n const type = this.type;\n const serialized = [type.kind];\n if (type.kind === 'array') {\n const itemType = type.itemType;\n if (itemType.kind === 'string' ||\n itemType.kind === 'number' ||\n itemType.kind === 'boolean') {\n serialized.push(itemType.kind);\n const N = type.N;\n if (typeof N === 'number' || this.args.length > 1) {\n serialized.push(N);\n }\n }\n }\n return serialized.concat(this.args.map(arg => arg.serialize()));\n }\n}\n\nexport default Assertion;\n","// @flow\n\nimport { NumberType, ValueType, FormattedType, array, StringType, ColorType } from '../types';\nimport Formatted, { FormattedSection } from '../types/formatted';\nimport { toString } from '../values';\n\nimport type { Expression } from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type { Type } from '../types';\n\ntype FormattedSectionExpression = {\n text: Expression,\n scale: Expression | null;\n font: Expression | null;\n textColor: Expression | null;\n}\n\nexport default class FormatExpression implements Expression {\n type: Type;\n sections: Array;\n\n constructor(sections: Array) {\n this.type = FormattedType;\n this.sections = sections;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length < 3) {\n return context.error(`Expected at least two arguments.`);\n }\n\n if ((args.length - 1) % 2 !== 0) {\n return context.error(`Expected an even number of arguments.`);\n }\n\n const sections: Array = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const text = context.parse(args[i], 1, ValueType);\n if (!text) return null;\n const kind = text.type.kind;\n if (kind !== 'string' && kind !== 'value' && kind !== 'null')\n return context.error(`Formatted text type must be 'string', 'value', or 'null'.`);\n\n const options = (args[i + 1]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`Format options argument must be an object.`);\n\n let scale = null;\n if (options['font-scale']) {\n scale = context.parse(options['font-scale'], 1, NumberType);\n if (!scale) return null;\n }\n\n let font = null;\n if (options['text-font']) {\n font = context.parse(options['text-font'], 1, array(StringType));\n if (!font) return null;\n }\n\n let textColor = null;\n if (options['text-color']) {\n textColor = context.parse(options['text-color'], 1, ColorType);\n if (!textColor) return null;\n }\n sections.push({text, scale, font, textColor});\n }\n\n return new FormatExpression(sections);\n }\n\n evaluate(ctx: EvaluationContext) {\n return new Formatted(\n this.sections.map(section =>\n new FormattedSection(\n toString(section.text.evaluate(ctx)),\n section.scale ? section.scale.evaluate(ctx) : null,\n section.font ? section.font.evaluate(ctx).join(',') : null,\n section.textColor ? section.textColor.evaluate(ctx) : null\n )\n )\n );\n }\n\n eachChild(fn: (Expression) => void) {\n for (const section of this.sections) {\n fn(section.text);\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\n possibleOutputs() {\n // Technically the combinatoric set of all children\n // Usually, this.text will be undefined anyway\n return [undefined];\n }\n\n serialize() {\n const serialized = [\"format\"];\n for (const section of this.sections) {\n serialized.push(section.text.serialize());\n const options = {};\n if (section.scale) {\n options['font-scale'] = section.scale.serialize();\n }\n if (section.font) {\n options['text-font'] = section.font.serialize();\n }\n if (section.textColor) {\n options['text-color'] = section.textColor.serialize();\n }\n serialized.push(options);\n }\n return serialized;\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport {BooleanType, ColorType, NumberType, StringType, ValueType} from '../types';\nimport {Color, toString as valueToString, validateRGBA} from '../values';\nimport RuntimeError from '../runtime_error';\nimport Formatted from '../types/formatted';\nimport FormatExpression from '../definitions/format';\n\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Value } from '../values';\nimport type { Type } from '../types';\n\nconst types = {\n 'to-boolean': BooleanType,\n 'to-color': ColorType,\n 'to-number': NumberType,\n 'to-string': StringType\n};\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 implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n const name: string = (args[0]: any);\n assert(types[name], name);\n\n if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const type = types[name];\n\n const parsed = [];\n for (let i = 1; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input) return null;\n parsed.push(input);\n }\n\n return new Coercion(type, parsed);\n }\n\n evaluate(ctx: EvaluationContext) {\n if (this.type.kind === 'boolean') {\n return Boolean(this.args[0].evaluate(ctx));\n } else if (this.type.kind === '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 } else if (typeof input === 'string') {\n const c = ctx.parseColor(input);\n if (c) return c;\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 } else {\n error = validateRGBA(input[0], input[1], input[2], input[3]);\n }\n if (!error) {\n return new Color((input[0]: any) / 255, (input[1]: any) / 255, (input[2]: any) / 255, (input[3]: any));\n }\n }\n }\n throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : String(JSON.stringify(input))}'`);\n } else if (this.type.kind === 'number') {\n let value = null;\n for (const arg of this.args) {\n value = arg.evaluate(ctx);\n if (value === null) return 0;\n const num = Number(value);\n if (isNaN(num)) continue;\n return num;\n }\n throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`);\n } else if (this.type.kind === '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(valueToString(this.args[0].evaluate(ctx)));\n } else {\n return valueToString(this.args[0].evaluate(ctx));\n }\n }\n\n eachChild(fn: (Expression) => void) {\n this.args.forEach(fn);\n }\n\n possibleOutputs(): Array {\n return [].concat(...this.args.map((arg) => arg.possibleOutputs()));\n }\n\n serialize() {\n if (this.type.kind === 'formatted') {\n return new FormatExpression([{text: this.args[0], scale: null, font: null, textColor: null}]).serialize();\n }\n const serialized = [`to-${this.type.kind}`];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Coercion;\n","// @flow\n\nimport { Color } from './values';\nimport type { FormattedSection } from './types/formatted';\nimport type { GlobalProperties, Feature, FeatureState } from './index';\n\nconst geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon'];\n\nclass EvaluationContext {\n globals: GlobalProperties;\n feature: ?Feature;\n featureState: ?FeatureState;\n formattedSection: ?FormattedSection;\n\n _parseColorCache: {[string]: ?Color};\n\n constructor() {\n this.globals = (null: any);\n this.feature = null;\n this.featureState = null;\n this.formattedSection = null;\n this._parseColorCache = {};\n }\n\n id() {\n return this.feature && 'id' in this.feature ? this.feature.id : null;\n }\n\n geometryType() {\n return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null;\n }\n\n properties() {\n return this.feature && this.feature.properties || {};\n }\n\n parseColor(input: string): ?Color {\n let cached = this._parseColorCache[input];\n if (!cached) {\n cached = this._parseColorCache[input] = Color.parse(input);\n }\n return cached;\n }\n}\n\nexport default EvaluationContext;\n","// @flow\n\nimport { toString } from './types';\n\nimport ParsingContext from './parsing_context';\nimport EvaluationContext from './evaluation_context';\nimport assert from 'assert';\n\nimport type { Expression, ExpressionRegistry } from './expression';\nimport type { Type } from './types';\nimport type { Value } from './values';\n\nexport type Varargs = {| type: Type |};\ntype Signature = Array | Varargs;\ntype Evaluate = (EvaluationContext, Array) => Value;\ntype Definition = [Type, Signature, Evaluate] |\n {|type: Type, overloads: Array<[Signature, Evaluate]>|};\n\nclass CompoundExpression implements Expression {\n name: string;\n type: Type;\n _evaluate: Evaluate;\n args: Array;\n\n static definitions: { [string]: Definition };\n\n constructor(name: string, type: Type, evaluate: Evaluate, args: Array) {\n this.name = name;\n this.type = type;\n this._evaluate = evaluate;\n this.args = args;\n }\n\n evaluate(ctx: EvaluationContext) {\n return this._evaluate(ctx, this.args);\n }\n\n eachChild(fn: (Expression) => void) {\n this.args.forEach(fn);\n }\n\n possibleOutputs() {\n return [undefined];\n }\n\n serialize(): Array {\n return [this.name].concat(this.args.map(arg => arg.serialize()));\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n const op: string = (args[0]: any);\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\n // Now check argument types against each signature\n const type = Array.isArray(definition) ?\n definition[0] : definition.type;\n\n const availableOverloads = Array.isArray(definition) ?\n [[definition[1], definition[2]]] :\n definition.overloads;\n\n const overloads = availableOverloads.filter(([signature]) => (\n !Array.isArray(signature) || // varags\n signature.length === args.length - 1 // correct param count\n ));\n\n let signatureContext: ParsingContext = (null: any);\n\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, context.path, null, context.scope);\n\n // First parse all the args, potentially coercing to the\n // types expected by this overload.\n const parsedArgs: Array = [];\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\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\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\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\n if (signatureContext.errors.length === 0) {\n return new CompoundExpression(op, type, evaluate, parsedArgs);\n }\n }\n\n assert(!signatureContext || signatureContext.errors.length > 0);\n\n if (overloads.length === 1) {\n context.errors.push(...signatureContext.errors);\n } else {\n const expected = overloads.length ? overloads : availableOverloads;\n const signatures = expected\n .map(([params]) => stringifySignature(params))\n .join(' | ');\n\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) return null;\n actualTypes.push(toString(parsed.type));\n }\n context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`);\n }\n\n return null;\n }\n\n static register(\n registry: ExpressionRegistry,\n definitions: { [string]: Definition }\n ) {\n assert(!CompoundExpression.definitions);\n CompoundExpression.definitions = definitions;\n for (const name in definitions) {\n registry[name] = CompoundExpression;\n }\n }\n}\n\nfunction stringifySignature(signature: Signature): string {\n if (Array.isArray(signature)) {\n return `(${signature.map(toString).join(', ')})`;\n } else {\n return `(${toString(signature.type)}...)`;\n }\n}\n\nexport default CompoundExpression;\n","// @flow\n\nimport { StringType, BooleanType, CollatorType } from '../types';\nimport Collator from '../types/collator';\n\nimport type { Expression } from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type { Type } from '../types';\n\nexport default class CollatorExpression implements Expression {\n type: Type;\n caseSensitive: Expression;\n diacriticSensitive: Expression;\n locale: Expression | null;\n\n constructor(caseSensitive: Expression, diacriticSensitive: Expression, locale: Expression | null) {\n this.type = CollatorType;\n this.locale = locale;\n this.caseSensitive = caseSensitive;\n this.diacriticSensitive = diacriticSensitive;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const options = (args[1]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`Collator options argument must be an object.`);\n\n const caseSensitive = context.parse(\n options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType);\n if (!caseSensitive) return null;\n\n const diacriticSensitive = context.parse(\n options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType);\n if (!diacriticSensitive) return null;\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n return new CollatorExpression(caseSensitive, diacriticSensitive, locale);\n }\n\n evaluate(ctx: EvaluationContext) {\n return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null);\n }\n\n eachChild(fn: (Expression) => void) {\n fn(this.caseSensitive);\n fn(this.diacriticSensitive);\n if (this.locale) {\n fn(this.locale);\n }\n }\n\n possibleOutputs() {\n // Technically the set of possible outputs is the combinatoric set of Collators produced\n // by all possibleOutputs of locale/caseSensitive/diacriticSensitive\n // But for the primary use of Collators in comparison operators, we ignore the Collator's\n // possibleOutputs anyway, so we can get away with leaving this undefined for now.\n return [undefined];\n }\n\n serialize() {\n const options = {};\n options['case-sensitive'] = this.caseSensitive.serialize();\n options['diacritic-sensitive'] = this.diacriticSensitive.serialize();\n if (this.locale) {\n options['locale'] = this.locale.serialize();\n }\n return [\"collator\", options];\n }\n}\n","// @flow\n\nimport CompoundExpression from './compound_expression';\n\nimport type { Expression } from './expression.js';\n\nfunction isFeatureConstant(e: Expression) {\n if (e instanceof CompoundExpression) {\n if (e.name === 'get' && e.args.length === 1) {\n return false;\n } else if (e.name === 'feature-state') {\n return false;\n } else if (e.name === 'has' && e.args.length === 1) {\n return false;\n } else if (\n e.name === 'properties' ||\n e.name === 'geometry-type' ||\n e.name === 'id'\n ) {\n return false;\n } else if (/^filter-/.test(e.name)) {\n return false;\n }\n }\n\n let result = true;\n e.eachChild(arg => {\n if (result && !isFeatureConstant(arg)) { result = false; }\n });\n return result;\n}\n\nfunction isStateConstant(e: Expression) {\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)) { result = false; }\n });\n return result;\n}\n\nfunction isGlobalPropertyConstant(e: Expression, properties: Array) {\n if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { return false; }\n let result = true;\n e.eachChild((arg) => {\n if (result && !isGlobalPropertyConstant(arg, properties)) { result = false; }\n });\n return result;\n}\n\nexport { isFeatureConstant, isGlobalPropertyConstant, isStateConstant };\n","// @flow\n\nimport type { Type } from '../types';\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\n\nclass Var implements Expression {\n type: Type;\n name: string;\n boundExpression: Expression;\n\n constructor(name: string, boundExpression: Expression) {\n this.type = boundExpression.type;\n this.name = name;\n this.boundExpression = boundExpression;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2 || typeof args[1] !== 'string')\n return context.error(`'var' expression requires exactly one string literal argument.`);\n\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\n return new Var(name, context.scope.get(name));\n }\n\n evaluate(ctx: EvaluationContext) {\n return this.boundExpression.evaluate(ctx);\n }\n\n eachChild() {}\n\n possibleOutputs() {\n return [undefined];\n }\n\n serialize() {\n return [\"var\", this.name];\n }\n}\n\nexport default Var;\n","// @flow\n\nimport Scope from './scope';\nimport { checkSubtype } from './types';\nimport ParsingError from './parsing_error';\nimport Literal from './definitions/literal';\nimport Assertion from './definitions/assertion';\nimport Coercion from './definitions/coercion';\nimport EvaluationContext from './evaluation_context';\nimport CompoundExpression from './compound_expression';\nimport CollatorExpression from './definitions/collator';\nimport {isGlobalPropertyConstant, isFeatureConstant} from './is_constant';\nimport Var from './definitions/var';\n\nimport type {Expression, ExpressionRegistry} from './expression';\nimport type {Type} from './types';\n\n/**\n * State associated parsing at a given point in an expression tree.\n * @private\n */\nclass ParsingContext {\n registry: ExpressionRegistry;\n path: Array;\n key: string;\n scope: Scope;\n errors: Array;\n\n // The expected type of this expression. Provided only to allow Expression\n // implementations to infer argument types: Expression#parse() need not\n // check that the output type of the parsed expression matches\n // `expectedType`.\n expectedType: ?Type;\n\n constructor(\n registry: ExpressionRegistry,\n path: Array = [],\n expectedType: ?Type,\n scope: Scope = new Scope(),\n errors: Array = []\n ) {\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 }\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(\n expr: mixed,\n index?: number,\n expectedType?: ?Type,\n bindings?: Array<[string, Expression]>,\n options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'} = {}\n ): ?Expression {\n if (index) {\n return this.concat(index, expectedType, bindings)._parse(expr, options);\n }\n return this._parse(expr, options);\n }\n\n _parse(expr: mixed, options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'}): ?Expression {\n if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') {\n expr = ['literal', expr];\n }\n\n function annotate(parsed, type, typeAnnotation: 'assert' | 'coerce' | 'omit') {\n if (typeAnnotation === 'assert') {\n return new Assertion(type, [parsed]);\n } else if (typeAnnotation === 'coerce') {\n return new Coercion(type, [parsed]);\n } else {\n return parsed;\n }\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\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\n const Expr = this.registry[op];\n if (Expr) {\n let parsed = Expr.parse(expr, this);\n if (!parsed) return null;\n\n if (this.expectedType) {\n const expected = this.expectedType;\n const actual = parsed.type;\n\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 } else if ((expected.kind === 'color' || expected.kind === 'formatted') && (actual.kind === 'value' || actual.kind === 'string')) {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');\n } else if (this.checkSubtype(expected, actual)) {\n return null;\n }\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.\n if (!(parsed instanceof Literal) && isConstant(parsed)) {\n const ec = new EvaluationContext();\n try {\n parsed = new Literal(parsed.type, parsed.evaluate(ec));\n } catch (e) {\n this.error(e.message);\n return null;\n }\n }\n\n return parsed;\n }\n\n return this.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n } else if (typeof expr === 'undefined') {\n return this.error(`'undefined' value invalid. Use null instead.`);\n } else if (typeof expr === 'object') {\n return this.error(`Bare objects invalid. Use [\"literal\", {...}] instead.`);\n } else {\n return this.error(`Expected an array, but found ${typeof expr} instead.`);\n }\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: number, expectedType?: ?Type, bindings?: Array<[string, Expression]>) {\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(\n this.registry,\n path,\n expectedType || null,\n scope,\n this.errors\n );\n }\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: string, ...keys: Array) {\n const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`;\n this.errors.push(new ParsingError(key, error));\n }\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 */\n checkSubtype(expected: Type, t: Type): ?string {\n const error = checkSubtype(expected, t);\n if (error) this.error(error);\n return error;\n }\n}\n\nexport default ParsingContext;\n\nfunction isConstant(expression: Expression) {\n if (expression instanceof Var) {\n return isConstant(expression.boundExpression);\n } else if (expression instanceof CompoundExpression && expression.name === 'error') {\n return false;\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\n const isTypeAnnotation = expression instanceof Coercion ||\n expression instanceof Assertion;\n\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\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 && isConstant(child);\n } else {\n childrenConstant = childrenConstant && child instanceof Literal;\n }\n });\n if (!childrenConstant) {\n return false;\n }\n\n return isFeatureConstant(expression) &&\n isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']);\n}\n","// @flow\n\nimport RuntimeError from './runtime_error';\n\nimport type { Expression } from './expression';\n\nexport type Stops = Array<[number, Expression]>;\n\n/**\n * Returns the index of the last stop <= input, or 0 if it doesn't exist.\n * @private\n */\nexport function findStopLessThanOrEqualTo(stops: Array, input: number) {\n const lastIndex = stops.length - 1;\n let lowerIndex = 0;\n let upperIndex = lastIndex;\n let currentIndex = 0;\n let currentValue, nextValue;\n\n while (lowerIndex <= upperIndex) {\n currentIndex = Math.floor((lowerIndex + upperIndex) / 2);\n currentValue = stops[currentIndex];\n nextValue = stops[currentIndex + 1];\n\n if (currentValue <= input) {\n if (currentIndex === lastIndex || input < nextValue) { // Search complete\n return currentIndex;\n }\n\n lowerIndex = currentIndex + 1;\n } else if (currentValue > input) {\n upperIndex = currentIndex - 1;\n } else {\n throw new RuntimeError('Input is not a number.');\n }\n }\n\n return 0;\n}\n","// @flow\n\nimport { NumberType } from '../types';\n\nimport { findStopLessThanOrEqualTo } from '../stops';\n\nimport type { Stops } from '../stops';\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Value } from '../values';\nimport type { Type } from '../types';\n\nclass Step implements Expression {\n type: Type;\n\n input: Expression;\n labels: Array;\n outputs: Array;\n\n constructor(type: Type, input: Expression, stops: Stops) {\n this.type = type;\n this.input = input;\n\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\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n\n if ((args.length - 1) % 2 !== 0) {\n return context.error(`Expected an even number of arguments.`);\n }\n\n const input = context.parse(args[1], 1, NumberType);\n if (!input) return null;\n\n const stops: Stops = [];\n\n let outputType: Type = (null: any);\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\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\n const labelKey = i;\n const valueKey = i + 1;\n\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\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\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n\n return new Step(outputType, input, stops);\n }\n\n evaluate(ctx: EvaluationContext) {\n const labels = this.labels;\n const outputs = this.outputs;\n\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n\n const value = ((this.input.evaluate(ctx): any): number);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\n\n const index = findStopLessThanOrEqualTo(labels, value);\n return outputs[index].evaluate(ctx);\n }\n\n eachChild(fn: (Expression) => void) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n\n possibleOutputs(): Array {\n return [].concat(...this.outputs.map((output) => output.possibleOutputs()));\n }\n\n serialize() {\n const serialized = [\"step\", this.input.serialize()];\n for (let i = 0; i < this.labels.length; i++) {\n if (i > 0) {\n serialized.push(this.labels[i]);\n }\n serialized.push(this.outputs[i].serialize());\n }\n return serialized;\n }\n}\n\nexport default Step;\n","// @flow\n\nimport Color from './color';\n\nexport function number(a: number, b: number, t: number) {\n return (a * (1 - t)) + (b * t);\n}\n\nexport function color(from: Color, to: Color, t: number) {\n return new Color(\n number(from.r, to.r, t),\n number(from.g, to.g, t),\n number(from.b, to.b, t),\n number(from.a, to.a, t)\n );\n}\n\nexport function array(from: Array, to: Array, t: number): Array {\n return from.map((d, i) => {\n return number(d, to[i], t);\n });\n}\n","// @flow\n\nimport Color from './color';\n\nimport {number as interpolateNumber} from './interpolate';\n\ntype LABColor = {\n l: number,\n a: number,\n b: number,\n alpha: number\n};\n\ntype HCLColor = {\n h: number,\n c: number,\n l: number,\n alpha: number\n};\n\n// Constants\nconst Xn = 0.950470, // D65 standard referent\n Yn = 1,\n Zn = 1.088830,\n t0 = 4 / 29,\n t1 = 6 / 29,\n t2 = 3 * t1 * t1,\n t3 = t1 * t1 * t1,\n deg2rad = Math.PI / 180,\n rad2deg = 180 / Math.PI;\n\n// Utilities\nfunction xyz2lab(t) {\n return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\n\nfunction lab2xyz(t) {\n return t > t1 ? t * t * t : t2 * (t - t0);\n}\n\nfunction xyz2rgb(x) {\n return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);\n}\n\nfunction rgb2xyz(x) {\n x /= 255;\n return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\n\n// LAB\nfunction rgbToLab(rgbColor: Color): LABColor {\n const b = rgb2xyz(rgbColor.r),\n a = rgb2xyz(rgbColor.g),\n l = rgb2xyz(rgbColor.b),\n x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn),\n y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn),\n z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn);\n\n return {\n l: 116 * y - 16,\n a: 500 * (x - y),\n b: 200 * (y - z),\n alpha: rgbColor.a\n };\n}\n\nfunction labToRgb(labColor: LABColor): Color {\n let y = (labColor.l + 16) / 116,\n x = isNaN(labColor.a) ? y : y + labColor.a / 500,\n z = isNaN(labColor.b) ? y : y - labColor.b / 200;\n y = Yn * lab2xyz(y);\n x = Xn * lab2xyz(x);\n z = Zn * lab2xyz(z);\n return new Color(\n xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB\n xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z),\n xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z),\n labColor.alpha\n );\n}\n\nfunction interpolateLab(from: LABColor, to: LABColor, t: number) {\n return {\n l: interpolateNumber(from.l, to.l, t),\n a: interpolateNumber(from.a, to.a, t),\n b: interpolateNumber(from.b, to.b, t),\n alpha: interpolateNumber(from.alpha, to.alpha, t)\n };\n}\n\n// HCL\nfunction rgbToHcl(rgbColor: Color): HCLColor {\n const {l, a, b} = rgbToLab(rgbColor);\n const h = Math.atan2(b, a) * rad2deg;\n return {\n h: h < 0 ? h + 360 : h,\n c: Math.sqrt(a * a + b * b),\n l,\n alpha: rgbColor.a\n };\n}\n\nfunction hclToRgb(hclColor: HCLColor): Color {\n const h = hclColor.h * deg2rad,\n c = hclColor.c,\n l = hclColor.l;\n return labToRgb({\n l,\n a: Math.cos(h) * c,\n b: Math.sin(h) * c,\n alpha: hclColor.alpha\n });\n}\n\nfunction interpolateHue(a: number, b: number, t: number) {\n const d = b - a;\n return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d);\n}\n\nfunction interpolateHcl(from: HCLColor, to: HCLColor, t: number) {\n return {\n h: interpolateHue(from.h, to.h, t),\n c: interpolateNumber(from.c, to.c, t),\n l: interpolateNumber(from.l, to.l, t),\n alpha: interpolateNumber(from.alpha, to.alpha, t)\n };\n}\n\nexport const lab = {\n forward: rgbToLab,\n reverse: labToRgb,\n interpolate: interpolateLab\n};\n\nexport const hcl = {\n forward: rgbToHcl,\n reverse: hclToRgb,\n interpolate: interpolateHcl\n};\n","// @flow\n\nimport UnitBezier from '@mapbox/unitbezier';\n\nimport * as interpolate from '../../util/interpolate';\nimport { toString, NumberType, ColorType } from '../types';\nimport { findStopLessThanOrEqualTo } from '../stops';\nimport { hcl, lab } from '../../util/color_spaces';\n\nimport type { Stops } from '../stops';\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Value } from '../values';\nimport type { Type } from '../types';\n\nexport type InterpolationType =\n { name: 'linear' } |\n { name: 'exponential', base: number } |\n { name: 'cubic-bezier', controlPoints: [number, number, number, number] };\n\nclass Interpolate implements Expression {\n type: Type;\n\n operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab';\n interpolation: InterpolationType;\n input: Expression;\n labels: Array;\n outputs: Array;\n\n constructor(type: Type, operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab', interpolation: InterpolationType, input: Expression, stops: Stops) {\n this.type = type;\n this.operator = operator;\n this.interpolation = interpolation;\n this.input = input;\n\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\n static interpolationFactor(interpolation: InterpolationType, input: number, lower: number, upper: number) {\n let t = 0;\n if (interpolation.name === 'exponential') {\n t = exponentialInterpolation(input, interpolation.base, lower, upper);\n } else if (interpolation.name === 'linear') {\n t = exponentialInterpolation(input, 1, lower, upper);\n } else if (interpolation.name === 'cubic-bezier') {\n const c = interpolation.controlPoints;\n const ub = new UnitBezier(c[0], c[1], c[2], c[3]);\n t = ub.solve(exponentialInterpolation(input, 1, lower, upper));\n }\n return t;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n let [operator, interpolation, input, ...rest] = args;\n\n if (!Array.isArray(interpolation) || interpolation.length === 0) {\n return context.error(`Expected an interpolation type expression.`, 1);\n }\n\n if (interpolation[0] === 'linear') {\n interpolation = { name: 'linear' };\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 } else if (interpolation[0] === 'cubic-bezier') {\n const controlPoints = interpolation.slice(1);\n if (\n controlPoints.length !== 4 ||\n controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)\n ) {\n return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1);\n }\n\n interpolation = {\n name: 'cubic-bezier',\n controlPoints: (controlPoints: any)\n };\n } else {\n return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0);\n }\n\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n\n if ((args.length - 1) % 2 !== 0) {\n return context.error(`Expected an even number of arguments.`);\n }\n\n input = context.parse(input, 2, NumberType);\n if (!input) return null;\n\n const stops: Stops = [];\n\n let outputType: Type = (null: any);\n if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') {\n outputType = ColorType;\n } else if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n for (let i = 0; i < rest.length; i += 2) {\n const label = rest[i];\n const value = rest[i + 1];\n\n const labelKey = i + 3;\n const valueKey = i + 4;\n\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\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\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n\n if (outputType.kind !== 'number' &&\n outputType.kind !== 'color' &&\n !(\n outputType.kind === 'array' &&\n outputType.itemType.kind === 'number' &&\n typeof outputType.N === 'number'\n )\n ) {\n return context.error(`Type ${toString(outputType)} is not interpolatable.`);\n }\n\n return new Interpolate(outputType, (operator: any), interpolation, input, stops);\n }\n\n evaluate(ctx: EvaluationContext) {\n const labels = this.labels;\n const outputs = this.outputs;\n\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n\n const value = ((this.input.evaluate(ctx): any): number);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\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\n const outputLower = outputs[index].evaluate(ctx);\n const outputUpper = outputs[index + 1].evaluate(ctx);\n\n if (this.operator === 'interpolate') {\n return (interpolate[this.type.kind.toLowerCase()]: any)(outputLower, outputUpper, t); // eslint-disable-line import/namespace\n } else if (this.operator === 'interpolate-hcl') {\n return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t));\n } else {\n return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t));\n }\n }\n\n eachChild(fn: (Expression) => void) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n\n possibleOutputs(): Array {\n return [].concat(...this.outputs.map((output) => output.possibleOutputs()));\n }\n\n serialize(): Array {\n let interpolation;\n if (this.interpolation.name === 'linear') {\n interpolation = [\"linear\"];\n } else if (this.interpolation.name === 'exponential') {\n if (this.interpolation.base === 1) {\n interpolation = [\"linear\"];\n } else {\n interpolation = [\"exponential\", this.interpolation.base];\n }\n } else {\n interpolation = [\"cubic-bezier\" ].concat(this.interpolation.controlPoints);\n }\n\n const serialized = [this.operator, interpolation, this.input.serialize()];\n\n for (let i = 0; i < this.labels.length; i++) {\n serialized.push(\n this.labels[i],\n this.outputs[i].serialize()\n );\n }\n return serialized;\n }\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\n if (difference === 0) {\n return 0;\n } else if (base === 1) {\n return progress / difference;\n } else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n\nexport default Interpolate;\n","// @flow\n\nimport assert from 'assert';\n\nimport { checkSubtype, ValueType } from '../types';\n\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Value } from '../values';\nimport type { Type } from '../types';\n\nclass Coalesce implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 2) {\n return context.error(\"Expectected at least one argument.\");\n }\n let outputType: Type = (null: any);\n const expectedType = context.expectedType;\n if (expectedType && expectedType.kind !== 'value') {\n outputType = expectedType;\n }\n const parsedArgs = [];\n\n for (const arg of args.slice(1)) {\n const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, {typeAnnotation: 'omit'});\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n parsedArgs.push(parsed);\n }\n assert(outputType);\n\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\n return needsAnnotation ?\n new Coalesce(ValueType, parsedArgs) :\n new Coalesce((outputType: any), parsedArgs);\n }\n\n evaluate(ctx: EvaluationContext) {\n let result = null;\n for (const arg of this.args) {\n result = arg.evaluate(ctx);\n if (result !== null) break;\n }\n return result;\n }\n\n eachChild(fn: (Expression) => void) {\n this.args.forEach(fn);\n }\n\n possibleOutputs(): Array {\n return [].concat(...this.args.map((arg) => arg.possibleOutputs()));\n }\n\n serialize() {\n const serialized = [\"coalesce\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Coalesce;\n","// @flow\n\nimport type { Type } from '../types';\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\n\nclass Let implements Expression {\n type: Type;\n bindings: Array<[string, Expression]>;\n result: Expression;\n\n constructor(bindings: Array<[string, Expression]>, result: Expression) {\n this.type = result.type;\n this.bindings = [].concat(bindings);\n this.result = result;\n }\n\n evaluate(ctx: EvaluationContext) {\n return this.result.evaluate(ctx);\n }\n\n eachChild(fn: (Expression) => void) {\n for (const binding of this.bindings) {\n fn(binding[1]);\n }\n fn(this.result);\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 4)\n return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`);\n\n const bindings: Array<[string, Expression]> = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const name = args[i];\n\n if (typeof name !== 'string') {\n return context.error(`Expected string, but found ${typeof name} instead.`, i);\n }\n\n if (/[^a-zA-Z0-9_]/.test(name)) {\n return context.error(`Variable names must contain only alphanumeric characters or '_'.`, i);\n }\n\n const value = context.parse(args[i + 1], i + 1);\n if (!value) return null;\n\n bindings.push([name, value]);\n }\n\n const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings);\n if (!result) return null;\n\n return new Let(bindings, result);\n }\n\n possibleOutputs() {\n return this.result.possibleOutputs();\n }\n\n serialize() {\n const serialized = [\"let\"];\n for (const [name, expr] of this.bindings) {\n serialized.push(name, expr.serialize());\n }\n serialized.push(this.result.serialize());\n return serialized;\n }\n}\n\nexport default Let;\n","// @flow\n\nimport { array, ValueType, NumberType } from '../types';\n\nimport RuntimeError from '../runtime_error';\n\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Type, ArrayType } from '../types';\nimport type { Value } from '../values';\n\nclass At implements Expression {\n type: Type;\n index: Expression;\n input: Expression;\n\n constructor(type: Type, index: Expression, input: Expression) {\n this.type = type;\n this.index = index;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 3)\n return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n\n const index = context.parse(args[1], 1, NumberType);\n const input = context.parse(args[2], 2, array(context.expectedType || ValueType));\n\n if (!index || !input) return null;\n\n const t: ArrayType = (input.type: any);\n return new At(t.itemType, index, input);\n }\n\n evaluate(ctx: EvaluationContext) {\n const index = ((this.index.evaluate(ctx): any): number);\n const array = ((this.input.evaluate(ctx): any): Array);\n\n if (index < 0) {\n throw new RuntimeError(`Array index out of bounds: ${index} < 0.`);\n }\n\n if (index >= array.length) {\n throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`);\n }\n\n if (index !== Math.floor(index)) {\n throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`);\n }\n\n return array[index];\n }\n\n eachChild(fn: (Expression) => void) {\n fn(this.index);\n fn(this.input);\n }\n\n possibleOutputs() {\n return [undefined];\n }\n\n serialize() {\n return [\"at\", this.index.serialize(), this.input.serialize()];\n }\n}\n\nexport default At;\n","// @flow\n\nimport assert from 'assert';\n\nimport { typeOf } from '../values';\nimport { ValueType, type Type } from '../types';\n\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Value } from '../values';\n\n// Map input label values to output expression index\ntype Cases = {[number | string]: number};\n\nclass Match implements Expression {\n type: Type;\n inputType: Type;\n\n input: Expression;\n cases: Cases;\n outputs: Array;\n otherwise: Expression;\n\n constructor(inputType: Type, outputType: Type, input: Expression, cases: Cases, outputs: Array, otherwise: Expression) {\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\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\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\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\n if (!Array.isArray(labels)) {\n labels = [labels];\n }\n\n const labelContext = context.concat(i);\n if (labels.length === 0) {\n return labelContext.error('Expected at least one branch label.');\n }\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 } 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 } else if (labelContext.checkSubtype(inputType, typeOf(label))) {\n return null;\n }\n\n if (typeof cases[String(label)] !== 'undefined') {\n return labelContext.error('Branch labels must be unique.');\n }\n\n cases[String(label)] = outputs.length;\n }\n\n const result = context.parse(value, i, outputType);\n if (!result) return null;\n outputType = outputType || result.type;\n outputs.push(result);\n }\n\n const input = context.parse(args[1], 1, ValueType);\n if (!input) return null;\n\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise) return null;\n\n assert(inputType && outputType);\n\n if (input.type.kind !== 'value' && context.concat(1).checkSubtype((inputType: any), input.type)) {\n return null;\n }\n\n return new Match((inputType: any), (outputType: any), input, cases, outputs, otherwise);\n }\n\n evaluate(ctx: EvaluationContext) {\n const input = (this.input.evaluate(ctx): any);\n const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise;\n return output.evaluate(ctx);\n }\n\n eachChild(fn: (Expression) => void) {\n fn(this.input);\n this.outputs.forEach(fn);\n fn(this.otherwise);\n }\n\n possibleOutputs(): Array {\n return []\n .concat(...this.outputs.map((out) => out.possibleOutputs()))\n .concat(this.otherwise.possibleOutputs());\n }\n\n serialize(): Array {\n const serialized = [\"match\", this.input.serialize()];\n\n // Sort so serialization has an arbitrary defined order, even though\n // branch order doesn't affect evaluation\n const sortedLabels = Object.keys(this.cases).sort();\n\n // Group branches by unique match expression to support condensed\n // serializations of the form [case1, case2, ...] -> matchExpression\n const groupedByOutput: Array<[number, Array]> = [];\n const outputLookup: {[index: number]: number} = {}; // lookup index into groupedByOutput for a given output expression\n for (const label of sortedLabels) {\n const outputIndex = outputLookup[this.cases[label]];\n if (outputIndex === undefined) {\n // First time seeing this output, add it to the end of the grouped list\n outputLookup[this.cases[label]] = groupedByOutput.length;\n groupedByOutput.push([this.cases[label], [label]]);\n } else {\n // We've seen this expression before, add the label to that output's group\n groupedByOutput[outputIndex][1].push(label);\n }\n }\n\n const coerceLabel = (label) => this.inputType.kind === 'number' ? Number(label) : label;\n\n for (const [outputIndex, labels] of groupedByOutput) {\n if (labels.length === 1) {\n // Only a single label matches this output expression\n serialized.push(coerceLabel(labels[0]));\n } else {\n // Array of literal labels pointing to this output expression\n serialized.push(labels.map(coerceLabel));\n }\n serialized.push(this.outputs[outputIndex].serialize());\n }\n serialized.push(this.otherwise.serialize());\n return serialized;\n }\n}\n\nexport default Match;\n","// @flow\n\nimport assert from 'assert';\n\nimport { BooleanType } from '../types';\n\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Value } from '../values';\nimport type { Type } from '../types';\n\ntype Branches = Array<[Expression, Expression]>;\n\nclass Case implements Expression {\n type: Type;\n\n branches: Branches;\n otherwise: Expression;\n\n constructor(type: Type, branches: Branches, otherwise: Expression) {\n this.type = type;\n this.branches = branches;\n this.otherwise = otherwise;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\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\n let outputType: ?Type;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\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) return null;\n\n const result = context.parse(args[i + 1], i + 1, outputType);\n if (!result) return null;\n\n branches.push([test, result]);\n\n outputType = outputType || result.type;\n }\n\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise) return null;\n\n assert(outputType);\n return new Case((outputType: any), branches, otherwise);\n }\n\n evaluate(ctx: EvaluationContext) {\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\n eachChild(fn: (Expression) => void) {\n for (const [test, expression] of this.branches) {\n fn(test);\n fn(expression);\n }\n fn(this.otherwise);\n }\n\n possibleOutputs(): Array {\n return []\n .concat(...this.branches.map(([_, out]) => out.possibleOutputs()))\n .concat(this.otherwise.possibleOutputs());\n }\n\n serialize() {\n const serialized = [\"case\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Case;\n","// @flow\n\nimport { toString, ValueType, BooleanType, CollatorType } from '../types';\nimport Assertion from './assertion';\nimport { typeOf } from '../values';\nimport RuntimeError from '../runtime_error';\n\nimport type { Expression } from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type { Type } from '../types';\n\ntype ComparisonOperator = '==' | '!=' | '<' | '>' | '<=' | '>=' ;\n\nfunction isComparableType(op: ComparisonOperator, type: 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 } else {\n // ordering operator\n return type.kind === 'string' ||\n type.kind === 'number' ||\n type.kind === 'value';\n }\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; }\n\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/**\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: ComparisonOperator, compareBasic, compareWithCollator) {\n const isOrderComparison = op !== '==' && op !== '!=';\n\n return class Comparison implements Expression {\n type: Type;\n lhs: Expression;\n rhs: Expression;\n collator: ?Expression;\n hasUntypedArgument: boolean;\n\n constructor(lhs: Expression, rhs: Expression, collator: ?Expression) {\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\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 3 && args.length !== 4)\n return context.error(`Expected two or three arguments.`);\n\n const op: ComparisonOperator = (args[0]: any);\n\n let lhs = context.parse(args[1], 1, ValueType);\n if (!lhs) return null;\n if (!isComparableType(op, lhs.type)) {\n return context.concat(1).error(`\"${op}\" comparisons are not supported for type '${toString(lhs.type)}'.`);\n }\n let rhs = context.parse(args[2], 2, ValueType);\n if (!rhs) return null;\n if (!isComparableType(op, rhs.type)) {\n return context.concat(2).error(`\"${op}\" comparisons are not supported for type '${toString(rhs.type)}'.`);\n }\n\n if (\n lhs.type.kind !== rhs.type.kind &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot compare types '${toString(lhs.type)}' and '${toString(rhs.type)}'.`);\n }\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 } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') {\n // (T, value)\n rhs = new Assertion(lhs.type, [rhs]);\n }\n }\n\n let collator = null;\n if (args.length === 4) {\n if (\n lhs.type.kind !== 'string' &&\n rhs.type.kind !== 'string' &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot use collator to compare non-string types.`);\n }\n collator = context.parse(args[3], 3, CollatorType);\n if (!collator) return null;\n }\n\n return new Comparison(lhs, rhs, collator);\n }\n\n evaluate(ctx: EvaluationContext) {\n const lhs = this.lhs.evaluate(ctx);\n const rhs = this.rhs.evaluate(ctx);\n\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\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\n return this.collator ?\n compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) :\n compareBasic(ctx, lhs, rhs);\n }\n\n eachChild(fn: (Expression) => void) {\n fn(this.lhs);\n fn(this.rhs);\n if (this.collator) {\n fn(this.collator);\n }\n }\n\n possibleOutputs() {\n return [true, false];\n }\n\n serialize() {\n const serialized = [op];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n };\n}\n\nexport const Equals = makeComparison('==', eq, eqCollate);\nexport const NotEquals = makeComparison('!=', neq, neqCollate);\nexport const LessThan = makeComparison('<', lt, ltCollate);\nexport const GreaterThan = makeComparison('>', gt, gtCollate);\nexport const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate);\nexport const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate);\n","// @flow\n\nimport { StringType, NumberType } from '../types';\n\nimport type { Expression } from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type { Type } from '../types';\n\ndeclare var Intl: {\n NumberFormat: Class\n};\n\ndeclare class Intl$NumberFormat {\n constructor (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n static (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n format(a: number): string;\n\n resolvedOptions(): any;\n}\n\ntype NumberFormatOptions = {\n style?: 'decimal' | 'currency' | 'percent';\n currency?: null | string;\n minimumFractionDigits?: null | string;\n maximumFractionDigits?: null | string;\n};\n\nexport default class NumberFormat implements Expression {\n type: Type;\n number: Expression;\n locale: Expression | null; // BCP 47 language tag\n currency: Expression | null; // ISO 4217 currency code, required if style=currency\n minFractionDigits: Expression | null; // Default 0\n maxFractionDigits: Expression | null; // Default 3\n\n constructor(number: Expression,\n locale: Expression | null,\n currency: Expression | null,\n minFractionDigits: Expression | null,\n maxFractionDigits: Expression | null) {\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\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 3)\n return context.error(`Expected two arguments.`);\n\n const number = context.parse(args[1], 1, NumberType);\n if (!number) return null;\n\n const options = (args[2]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`NumberFormat options argument must be an object.`);\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n let currency = null;\n if (options['currency']) {\n currency = context.parse(options['currency'], 1, StringType);\n if (!currency) return null;\n }\n\n let minFractionDigits = null;\n if (options['min-fraction-digits']) {\n minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType);\n if (!minFractionDigits) return null;\n }\n\n let maxFractionDigits = null;\n if (options['max-fraction-digits']) {\n maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType);\n if (!maxFractionDigits) return null;\n }\n\n return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits);\n }\n\n evaluate(ctx: EvaluationContext) {\n return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [],\n {\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\n eachChild(fn: (Expression) => void) {\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\n possibleOutputs() {\n return [undefined];\n }\n\n serialize() {\n const options = {};\n if (this.locale) {\n options['locale'] = this.locale.serialize();\n }\n if (this.currency) {\n options['currency'] = this.currency.serialize();\n }\n if (this.minFractionDigits) {\n options['min-fraction-digits'] = this.minFractionDigits.serialize();\n }\n if (this.maxFractionDigits) {\n options['max-fraction-digits'] = this.maxFractionDigits.serialize();\n }\n return [\"number-format\", this.number.serialize(), options];\n }\n}\n","// @flow\n\nimport { NumberType, toString } from '../types';\n\nimport { typeOf } from '../values';\nimport RuntimeError from '../runtime_error';\n\nimport type { Expression } from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Type } from '../types';\n\nclass Length implements Expression {\n type: Type;\n input: Expression;\n\n constructor(input: Expression) {\n this.type = NumberType;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2)\n return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);\n\n const input = context.parse(args[1], 1);\n if (!input) return null;\n\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(input.type)} instead.`);\n\n return new Length(input);\n }\n\n evaluate(ctx: EvaluationContext) {\n const input = this.input.evaluate(ctx);\n if (typeof input === 'string') {\n return input.length;\n } else if (Array.isArray(input)) {\n return input.length;\n } else {\n throw new RuntimeError(`Expected value to be of type string or array, but found ${toString(typeOf(input))} instead.`);\n }\n }\n\n eachChild(fn: (Expression) => void) {\n fn(this.input);\n }\n\n possibleOutputs() {\n return [undefined];\n }\n\n serialize() {\n const serialized = [\"length\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Length;\n","// @flow\n\nimport {\n type Type,\n NumberType,\n StringType,\n BooleanType,\n ColorType,\n ObjectType,\n ValueType,\n ErrorType,\n CollatorType,\n array,\n toString as typeToString\n} from '../types';\n\nimport { typeOf, Color, validateRGBA, toString as valueToString } from '../values';\nimport CompoundExpression from '../compound_expression';\nimport RuntimeError from '../runtime_error';\nimport Let from './let';\nimport Var from './var';\nimport Literal from './literal';\nimport Assertion from './assertion';\nimport Coercion from './coercion';\nimport At from './at';\nimport Match from './match';\nimport Case from './case';\nimport Step from './step';\nimport Interpolate from './interpolate';\nimport Coalesce from './coalesce';\nimport {\n Equals,\n NotEquals,\n LessThan,\n GreaterThan,\n LessThanOrEqual,\n GreaterThanOrEqual\n} from './comparison';\nimport CollatorExpression from './collator';\nimport NumberFormat from './number_format';\nimport FormatExpression from './format';\nimport Length from './length';\n\nimport type { Varargs } from '../compound_expression';\nimport type { ExpressionRegistry } from '../expression';\n\nconst expressions: ExpressionRegistry = {\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 '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 '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};\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) throw new RuntimeError(error);\n return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha);\n}\n\nfunction has(key, obj) {\n return key in obj;\n}\n\nfunction get(key, obj) {\n const v = obj[key];\n return typeof v === 'undefined' ? null : v;\n}\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}\n\nfunction varargs(type: Type): Varargs {\n return { type };\n}\n\nCompoundExpression.register(expressions, {\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]) => typeToString(typeOf(v.evaluate(ctx)))\n ],\n 'to-rgba': [\n array(NumberType, 4),\n [ColorType],\n (ctx, [v]) => {\n return v.evaluate(ctx).toArray();\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: any).value] === (v: any).value\n ],\n 'filter-id-==': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => ctx.id() === (v: any).value\n ],\n 'filter-type-==': [\n BooleanType,\n [StringType],\n (ctx, [v]) => ctx.geometryType() === (v: any).value\n ],\n 'filter-<': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).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: any).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: any).value];\n const b = (v: any).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: any).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: any).value];\n const b = (v: any).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: any).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: any).value];\n const b = (v: any).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: any).value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-has': [\n BooleanType,\n [ValueType],\n (ctx, [k]) => (k: any).value in ctx.properties()\n ],\n 'filter-has-id': [\n BooleanType,\n [],\n (ctx) => ctx.id() !== null\n ],\n 'filter-type-in': [\n BooleanType,\n [array(StringType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.geometryType()) >= 0\n ],\n 'filter-id-in': [\n BooleanType,\n [array(ValueType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.id()) >= 0\n ],\n 'filter-in-small': [\n BooleanType,\n [StringType, array(ValueType)],\n // assumes v is an array literal\n (ctx, [k, v]) => (v: any).value.indexOf(ctx.properties()[(k: any).value]) >= 0\n ],\n 'filter-in-large': [\n BooleanType,\n [StringType, array(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: any).value], (v: any).value, 0, (v: any).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 => valueToString(arg.evaluate(ctx))).join('')\n ],\n 'resolved-locale': [\n StringType,\n [CollatorType],\n (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()\n ]\n});\n\nexport default expressions;\n","// @flow\n\n/**\n * A type used for returning and propagating errors. The first element of the union\n * represents success and contains a value, and the second represents an error and\n * contains an error value.\n * @private\n */\nexport type Result =\n | {| result: 'success', value: T |}\n | {| result: 'error', value: E |};\n\nexport function success(value: T): Result {\n return { result: 'success', value };\n}\n\nexport function error(value: E): Result {\n return { result: 'error', value };\n}\n","// @flow\n\nimport type {StylePropertySpecification} from '../style-spec';\n\nexport function supportsPropertyExpression(spec: StylePropertySpecification): boolean {\n return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven';\n}\n\nexport function supportsZoomExpression(spec: StylePropertySpecification): boolean {\n return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1;\n}\n\nexport function supportsInterpolation(spec: StylePropertySpecification): boolean {\n return !!spec.expression && spec.expression.interpolated;\n}\n","\nexport default function getType(val) {\n if (val instanceof Number) {\n return 'number';\n } else if (val instanceof String) {\n return 'string';\n } else if (val instanceof Boolean) {\n return 'boolean';\n } else if (Array.isArray(val)) {\n return 'array';\n } else if (val === null) {\n return 'null';\n } else {\n return typeof val;\n }\n}\n","\nimport * as colorSpaces from '../util/color_spaces';\nimport Color from '../util/color';\nimport extend from '../util/extend';\nimport getType from '../util/get_type';\nimport * as interpolate from '../util/interpolate';\nimport Interpolate from '../expression/definitions/interpolate';\nimport Formatted from '../expression/types/formatted';\nimport { supportsInterpolation } from '../util/properties';\nimport { findStopLessThanOrEqualTo } from '../expression/stops';\n\nexport function isFunction(value) {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction identityFunction(x) {\n return x;\n}\n\nexport function 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\n if (isColor) {\n parameters = extend({}, parameters);\n\n if (parameters.stops) {\n parameters.stops = parameters.stops.map((stop) => {\n return [stop[0], Color.parse(stop[1])];\n });\n }\n\n if (parameters.default) {\n parameters.default = Color.parse(parameters.default);\n } else {\n parameters.default = Color.parse(propertySpec.default);\n }\n }\n\n if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { // eslint-disable-line import/namespace\n throw new Error(`Unknown color space: ${parameters.colorSpace}`);\n }\n\n let innerFun;\n let hashedStops;\n let categoricalKeyType;\n if (type === 'exponential') {\n innerFun = evaluateExponentialFunction;\n } else if (type === 'interval') {\n innerFun = evaluateIntervalFunction;\n } else if (type === 'categorical') {\n innerFun = evaluateCategoricalFunction;\n\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\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 } else {\n throw new Error(`Unknown function type \"${type}\"`);\n }\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\n const featureFunctionStops = [];\n for (const z of zoomStops) {\n featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]);\n }\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 } 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 } 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(parameters.default, propertySpec.default);\n }\n return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType);\n }\n };\n }\n}\n\nfunction coalesce(a, b, c) {\n if (a !== undefined) return a;\n if (b !== undefined) return b;\n if (c !== undefined) return c;\n}\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(evaluated, parameters.default, propertySpec.default);\n}\n\nfunction evaluateIntervalFunction(parameters, propertySpec, input) {\n // Edge cases\n if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1) return parameters.stops[0][1];\n if (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n\n return parameters.stops[index][1];\n}\n\nfunction evaluateExponentialFunction(parameters, propertySpec, input) {\n const base = parameters.base !== undefined ? parameters.base : 1;\n\n // Edge cases\n if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1) return parameters.stops[0][1];\n if (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n const t = interpolationFactor(\n input, base,\n parameters.stops[index][0],\n parameters.stops[index + 1][0]);\n\n const outputLower = parameters.stops[index][1];\n const outputUpper = parameters.stops[index + 1][1];\n let interp = interpolate[propertySpec.type] || identityFunction; // eslint-disable-line import/namespace\n\n if (parameters.colorSpace && parameters.colorSpace !== 'rgb') {\n const colorspace = colorSpaces[parameters.colorSpace]; // eslint-disable-line import/namespace\n interp = (a, b) => colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t));\n }\n\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);\n }\n };\n }\n\n return interp(outputLower, outputUpper, t);\n}\n\nfunction evaluateIdentityFunction(parameters, propertySpec, input) {\n if (propertySpec.type === 'color') {\n input = Color.parse(input);\n } else if (propertySpec.type === 'formatted') {\n input = Formatted.fromString(input.toString());\n } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) {\n input = undefined;\n }\n return coalesce(input, parameters.default, propertySpec.default);\n}\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\n if (difference === 0) {\n return 0;\n } else if (base === 1) {\n return progress / difference;\n } else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport extend from '../util/extend';\nimport ParsingError from './parsing_error';\nimport ParsingContext from './parsing_context';\nimport EvaluationContext from './evaluation_context';\nimport CompoundExpression from './compound_expression';\nimport Step from './definitions/step';\nimport Interpolate from './definitions/interpolate';\nimport Coalesce from './definitions/coalesce';\nimport Let from './definitions/let';\nimport definitions from './definitions';\nimport * as isConstant from './is_constant';\nimport RuntimeError from './runtime_error';\nimport { success, error } from '../util/result';\nimport { supportsPropertyExpression, supportsZoomExpression, supportsInterpolation } from '../util/properties';\n\nimport type {Type, EvaluationKind} from './types';\nimport type {Value} from './values';\nimport type {Expression} from './expression';\nimport type {StylePropertySpecification} from '../style-spec';\nimport type {Result} from '../util/result';\nimport type {InterpolationType} from './definitions/interpolate';\nimport type {PropertyValueSpecification} from '../types';\nimport type {FormattedSection} from './types/formatted';\n\nexport type Feature = {\n +type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon',\n +id?: any,\n +properties: {[string]: any},\n +patterns?: {[string]: {\"min\": string, \"mid\": string, \"max\": string}}\n};\n\nexport type FeatureState = {[string]: any};\n\nexport type GlobalProperties = $ReadOnly<{\n zoom: number,\n heatmapDensity?: number,\n lineProgress?: number,\n isSupportedScript?: (string) => boolean,\n accumulated?: Value\n}>;\n\nexport class StyleExpression {\n expression: Expression;\n\n _evaluator: EvaluationContext;\n _defaultValue: Value;\n _warningHistory: {[key: string]: boolean};\n _enumValues: ?{[string]: any};\n\n constructor(expression: Expression, propertySpec: ?StylePropertySpecification) {\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\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, formattedSection?: FormattedSection): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature;\n this._evaluator.featureState = featureState;\n this._evaluator.formattedSection = formattedSection;\n\n return this.expression.evaluate(this._evaluator);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, formattedSection?: FormattedSection): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature || null;\n this._evaluator.featureState = featureState || null;\n this._evaluator.formattedSection = formattedSection || null;\n\n try {\n const val = this.expression.evaluate(this._evaluator);\n if (val === null || val === undefined) {\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 } 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}\n\nexport function isExpression(expression: mixed) {\n return Array.isArray(expression) && expression.length > 0 &&\n typeof expression[0] === 'string' && expression[0] in definitions;\n}\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 */\nexport function createExpression(expression: mixed, propertySpec: ?StylePropertySpecification): Result> {\n const parser = new ParsingContext(definitions, [], propertySpec ? getExpectedType(propertySpec) : undefined);\n\n // For string-valued properties, coerce to string at the top level rather than asserting.\n const parsed = parser.parse(expression, undefined, undefined, undefined,\n propertySpec && propertySpec.type === 'string' ? {typeAnnotation: 'coerce'} : undefined);\n\n if (!parsed) {\n assert(parser.errors.length > 0);\n return error(parser.errors);\n }\n\n return success(new StyleExpression(parsed, propertySpec));\n}\n\nexport class ZoomConstantExpression {\n kind: Kind;\n isStateDependent: boolean;\n _styleExpression: StyleExpression;\n\n constructor(kind: Kind, expression: StyleExpression) {\n this.kind = kind;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('constant': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, formattedSection);\n }\n}\n\nexport class ZoomDependentExpression {\n kind: Kind;\n zoomStops: Array;\n isStateDependent: boolean;\n\n _styleExpression: StyleExpression;\n interpolationType: ?InterpolationType;\n\n constructor(kind: Kind, expression: StyleExpression, zoomStops: Array, interpolationType?: InterpolationType) {\n this.kind = kind;\n this.zoomStops = zoomStops;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('camera': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n this.interpolationType = interpolationType;\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, formattedSection);\n }\n\n interpolationFactor(input: number, lower: number, upper: number): number {\n if (this.interpolationType) {\n return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);\n } else {\n return 0;\n }\n }\n}\n\nexport type ConstantExpression = {\n kind: 'constant',\n +evaluate: (globals: GlobalProperties, feature?: Feature) => any,\n}\n\nexport type SourceExpression = {\n kind: 'source',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, formattedSection?: FormattedSection) => any,\n};\n\nexport type CameraExpression = {\n kind: 'camera',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array,\n interpolationType: ?InterpolationType\n};\n\nexport type CompositeExpression = {\n kind: 'composite',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, formattedSection?: FormattedSection) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array,\n interpolationType: ?InterpolationType\n};\n\nexport type StylePropertyExpression =\n | ConstantExpression\n | SourceExpression\n | CameraExpression\n | CompositeExpression;\n\nexport function createPropertyExpression(expression: mixed, propertySpec: StylePropertySpecification): Result> {\n expression = createExpression(expression, propertySpec);\n if (expression.result === 'error') {\n return expression;\n }\n\n const parsed = expression.value.expression;\n\n const isFeatureConstant = isConstant.isFeatureConstant(parsed);\n if (!isFeatureConstant && !supportsPropertyExpression(propertySpec)) {\n return error([new ParsingError('', 'data expressions not supported')]);\n }\n\n const isZoomConstant = isConstant.isGlobalPropertyConstant(parsed, ['zoom']);\n if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {\n return error([new ParsingError('', 'zoom expressions not supported')]);\n }\n\n const zoomCurve = findZoomCurve(parsed);\n if (!zoomCurve && !isZoomConstant) {\n return error([new ParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.')]);\n } else if (zoomCurve instanceof ParsingError) {\n return error([zoomCurve]);\n } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) {\n return error([new ParsingError('', '\"interpolate\" expressions cannot be used with this property')]);\n }\n\n if (!zoomCurve) {\n return success(isFeatureConstant ?\n (new ZoomConstantExpression('constant', expression.value): ConstantExpression) :\n (new ZoomConstantExpression('source', expression.value): SourceExpression));\n }\n\n const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined;\n\n return success(isFeatureConstant ?\n (new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType): CameraExpression) :\n (new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType): CompositeExpression));\n}\n\nimport { isFunction, createFunction } from '../function';\nimport { Color } from './values';\n\n// serialization wrapper for old-style stop functions normalized to the\n// expression interface\nexport class StylePropertyFunction {\n _parameters: PropertyValueSpecification;\n _specification: StylePropertySpecification;\n\n kind: EvaluationKind;\n evaluate: (globals: GlobalProperties, feature?: Feature) => any;\n interpolationFactor: ?(input: number, lower: number, upper: number) => number;\n zoomStops: ?Array;\n\n constructor(parameters: PropertyValueSpecification, specification: StylePropertySpecification) {\n this._parameters = parameters;\n this._specification = specification;\n extend(this, createFunction(this._parameters, this._specification));\n }\n\n static deserialize(serialized: {_parameters: PropertyValueSpecification, _specification: StylePropertySpecification}) {\n return ((new StylePropertyFunction(serialized._parameters, serialized._specification)): StylePropertyFunction);\n }\n\n static serialize(input: StylePropertyFunction) {\n return {\n _parameters: input._parameters,\n _specification: input._specification\n };\n }\n}\n\nexport function normalizePropertyExpression(value: PropertyValueSpecification, specification: StylePropertySpecification): StylePropertyExpression {\n if (isFunction(value)) {\n return (new StylePropertyFunction(value, specification): any);\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: any = value;\n if (typeof value === 'string' && specification.type === 'color') {\n constant = Color.parse(value);\n }\n return {\n kind: 'constant',\n evaluate: () => constant\n };\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: Expression): Step | Interpolate | ParsingError | null {\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\n result = expression;\n }\n\n if (result instanceof ParsingError) {\n return result;\n }\n\n expression.eachChild((child) => {\n const childResult = findZoomCurve(child);\n if (childResult instanceof ParsingError) {\n result = childResult;\n } else if (!result && childResult) {\n result = new ParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.');\n } else if (result && childResult && result !== childResult) {\n result = new ParsingError('', 'Only one zoom-based \"step\" or \"interpolate\" subexpression may be used in an expression.');\n }\n });\n\n return result;\n}\n\nimport { ColorType, StringType, NumberType, BooleanType, ValueType, FormattedType, array } from './types';\n\nfunction getExpectedType(spec: StylePropertySpecification): Type {\n const types = {\n color: ColorType,\n string: StringType,\n number: NumberType,\n enum: StringType,\n boolean: BooleanType,\n formatted: FormattedType\n };\n\n if (spec.type === 'array') {\n return array(types[spec.value] || ValueType, spec.length);\n }\n\n return types[spec.type];\n}\n\nfunction getDefaultValue(spec: StylePropertySpecification): Value {\n if (spec.type === 'color' && isFunction(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 } else if (spec.type === 'color') {\n return Color.parse(spec.default) || null;\n } else if (spec.default === undefined) {\n return null;\n } else {\n return spec.default;\n }\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validateSpec from './validate';\n\nexport default function 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 let errors = [];\n\n const type = getType(object);\n if (type !== 'object') {\n return [new ValidationError(key, object, `object expected, ${type} found`)];\n }\n\n for (const objectKey in object) {\n const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint'\n const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*'];\n\n let validateElement;\n if (elementValidators[elementSpecKey]) {\n validateElement = elementValidators[elementSpecKey];\n } else if (elementSpecs[elementSpecKey]) {\n validateElement = validateSpec;\n } else if (elementValidators['*']) {\n validateElement = elementValidators['*'];\n } else if (elementSpecs['*']) {\n validateElement = validateSpec;\n } else {\n errors.push(new ValidationError(key, object[objectKey], `unknown property \"${objectKey}\"`));\n continue;\n }\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 }, object));\n }\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\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\n return errors;\n}\n","\nimport getType from '../util/get_type';\nimport validate from './validate';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateArray(options) {\n const array = options.value;\n const arraySpec = options.valueSpec;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const key = options.key;\n const validateArrayElement = options.arrayElementValidator || validate;\n\n if (getType(array) !== 'array') {\n return [new ValidationError(key, array, `array expected, ${getType(array)} found`)];\n }\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\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\n let arrayElementSpec = {\n \"type\": arraySpec.value,\n \"values\": arraySpec.values\n };\n\n if (styleSpec.$version < 7) {\n arrayElementSpec.function = arraySpec.function;\n }\n\n if (getType(arraySpec.value) === 'object') {\n arrayElementSpec = arraySpec.value;\n }\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 style,\n styleSpec,\n key: `${key}[${i}]`\n }));\n }\n return errors;\n}\n","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateNumber(options) {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n const type = getType(value);\n\n if (type !== 'number') {\n return [new ValidationError(key, value, `number expected, ${type} found`)];\n }\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\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\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validate from './validate';\nimport validateObject from './validate_object';\nimport validateArray from './validate_array';\nimport validateNumber from './validate_number';\nimport { isExpression } from '../expression';\nimport { unbundle, deepUnbundle } from '../util/unbundle_jsonlint';\nimport {\n supportsPropertyExpression,\n supportsZoomExpression,\n supportsInterpolation\n} from '../util/properties';\n\nexport default function 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\n const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined;\n const isPropertyFunction = !isZoomFunction;\n const isZoomAndPropertyFunction =\n getType(options.value.stops) === 'array' &&\n getType(options.value.stops[0]) === 'array' &&\n getType(options.value.stops[0][0]) === 'object';\n\n const errors = validateObject({\n key: options.key,\n value: options.value,\n valueSpec: options.styleSpec.function,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n stops: validateFunctionStops,\n default: validateFunctionDefault\n }\n });\n\n if (functionType === 'identity' && isZoomFunction) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"property\"'));\n }\n\n if (functionType !== 'identity' && !options.value.stops) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"stops\"'));\n }\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\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 } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported'));\n }\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\n return errors;\n\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\n let errors = [];\n const value = options.value;\n\n errors = errors.concat(validateArray({\n key: options.key,\n value,\n valueSpec: options.valueSpec,\n style: options.style,\n styleSpec: options.styleSpec,\n arrayElementValidator: validateFunctionStop\n }));\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\n return errors;\n }\n\n function validateFunctionStop(options) {\n let errors = [];\n const value = options.value;\n const key = options.key;\n\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n\n if (value.length !== 2) {\n return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)];\n }\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 style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: { zoom: validateNumber, value: validateStopDomainValue }\n }));\n } else {\n errors = errors.concat(validateStopDomainValue({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: {},\n style: options.style,\n styleSpec: options.styleSpec\n }, value));\n }\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\n return errors.concat(validate({\n key: `${key}[1]`,\n value: value[1],\n valueSpec: functionValueSpec,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n }\n\n function validateStopDomainValue(options, stop) {\n const type = getType(options.value);\n const value = unbundle(options.value);\n\n const reportValue = options.value !== null ? options.value : stop;\n\n if (!stopKeyType) {\n stopKeyType = type;\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\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\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\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\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 } else {\n previousStopDomainValue = value;\n }\n\n if (functionType === 'categorical' && value in stopDomainValues) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')];\n } else {\n stopDomainValues[value] = true;\n }\n\n return [];\n }\n\n function validateFunctionDefault(options) {\n return validate({\n key: options.key,\n value: options.value,\n valueSpec: functionValueSpec,\n style: options.style,\n styleSpec: options.styleSpec\n });\n }\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error';\n\nimport { createExpression, createPropertyExpression } from '../expression';\nimport { deepUnbundle } from '../util/unbundle_jsonlint';\nimport { isStateConstant, isGlobalPropertyConstant, isFeatureConstant } from '../expression/is_constant';\n\nexport default function validateExpression(options: any): Array {\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\n const expressionObj = (expression.value: any).expression || (expression.value: any)._styleExpression.expression;\n\n if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') &&\n expressionObj.possibleOutputs().indexOf(undefined) !== -1) {\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\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\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\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\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport { unbundle } from '../util/unbundle_jsonlint';\n\nexport default function validateEnum(options) {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n const errors = [];\n\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 } 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","// @flow\n\nimport { createExpression } from '../expression';\n\nimport type {GlobalProperties} from '../expression';\nexport type FeatureFilter = (globalProperties: GlobalProperties, feature: VectorTileFeature) => boolean;\n\nexport default createFilter;\nexport { isExpressionFilter };\n\nfunction isExpressionFilter(filter: any) {\n if (filter === true || filter === false) {\n return true;\n }\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\n case 'in':\n case '!in':\n case '!has':\n case 'none':\n return false;\n\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\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\n default:\n return true;\n }\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/**\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 mapbox gl filter\n * @returns {Function} filter-evaluating function\n */\nfunction createFilter(filter: any): FeatureFilter {\n if (filter === null || filter === undefined) {\n return () => true;\n }\n\n if (!isExpressionFilter(filter)) {\n filter = convertFilter(filter);\n }\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 } else {\n return (globalProperties: GlobalProperties, feature: VectorTileFeature) => compiled.value.evaluate(globalProperties, feature);\n }\n}\n\n// Comparison function to sort numbers and strings\nfunction compare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction convertFilter(filter: ?Array): mixed {\n if (!filter) return true;\n const op = filter[0];\n if (filter.length <= 1) return (op !== 'any');\n const converted =\n op === '==' ? convertComparisonOp(filter[1], filter[2], '==') :\n op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) :\n op === '<' ||\n op === '>' ||\n op === '<=' ||\n op === '>=' ? convertComparisonOp(filter[1], filter[2], op) :\n op === 'any' ? convertDisjunctionOp(filter.slice(1)) :\n op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) :\n op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) :\n op === 'in' ? convertInOp(filter[1], filter.slice(2)) :\n op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) :\n op === 'has' ? convertHasOp(filter[1]) :\n op === '!has' ? convertNegation(convertHasOp(filter[1])) :\n true;\n return converted;\n}\n\nfunction convertComparisonOp(property: string, value: any, op: string) {\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}\n\nfunction convertDisjunctionOp(filters: Array>) {\n return ['any'].concat(filters.map(convertFilter));\n}\n\nfunction convertInOp(property: string, values: Array) {\n if (values.length === 0) { return false; }\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 } else {\n return ['filter-in-small', property, ['literal', values]];\n }\n }\n}\n\nfunction convertHasOp(property: string) {\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}\n\nfunction convertNegation(filter: mixed) {\n return ['!', filter];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport validateExpression from './validate_expression';\nimport validateEnum from './validate_enum';\nimport getType from '../util/get_type';\nimport { unbundle, deepUnbundle } from '../util/unbundle_jsonlint';\nimport extend from '../util/extend';\nimport { isExpressionFilter } from '../feature_filter';\n\nexport default function validateFilter(options) {\n if (isExpressionFilter(deepUnbundle(options.value))) {\n return validateExpression(extend({}, options, {\n expressionContext: 'filter',\n valueSpec: { value: 'boolean' }\n }));\n } else {\n return validateNonExpressionFilter(options);\n }\n}\n\nfunction validateNonExpressionFilter(options) {\n const value = options.value;\n const key = options.key;\n\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n\n const styleSpec = options.styleSpec;\n let type;\n\n let errors = [];\n\n if (value.length < 1) {\n return [new ValidationError(key, value, 'filter array must have at least 1 element')];\n }\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\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 } 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\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\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 } else if (type !== 'string') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n }\n break;\n\n }\n\n return errors;\n}\n","\nimport validate from './validate';\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport { isFunction } from '../function';\nimport { unbundle, deepUnbundle } from '../util/unbundle_jsonlint';\nimport { supportsPropertyExpression } from '../util/properties';\n\nexport default function validateProperty(options, propertyType) {\n const key = options.key;\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\n if (!layerSpec) return [];\n\n const transitionMatch = propertyKey.match(/^(.*)-transition$/);\n if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) {\n return validate({\n key,\n value,\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n });\n }\n\n const valueSpec = options.valueSpec || layerSpec[propertyKey];\n if (!valueSpec) {\n return [new ValidationError(key, value, `unknown property \"${propertyKey}\"`)];\n }\n\n let tokenMatch;\n if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) {\n return [new ValidationError(\n key, value,\n `\"${propertyKey}\" does not support interpolation syntax\\n` +\n `Use an identity property function instead: \\`{ \"type\": \"identity\", \"property\": ${JSON.stringify(tokenMatch[1])} }\\`.`)];\n }\n\n const errors = [];\n\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(deepUnbundle(value)) && unbundle(value.type) === 'identity') {\n errors.push(new ValidationError(key, value, '\"text-font\" does not support identity functions'));\n }\n }\n\n return errors.concat(validate({\n key: options.key,\n value,\n valueSpec,\n style,\n styleSpec,\n expressionContext: 'property',\n propertyType,\n propertyKey\n }));\n}\n","\nimport validateProperty from './validate_property';\n\nexport default function validatePaintProperty(options) {\n return validateProperty(options, 'paint');\n}\n","\nimport validateProperty from './validate_property';\n\nexport default function validateLayoutProperty(options) {\n return validateProperty(options, 'layout');\n}\n","\nimport ValidationError from '../error/validation_error';\nimport { unbundle } from '../util/unbundle_jsonlint';\nimport validateObject from './validate_object';\nimport validateFilter from './validate_filter';\nimport validatePaintProperty from './validate_paint_property';\nimport validateLayoutProperty from './validate_layout_property';\nimport validateSpec from './validate';\nimport extend from '../util/extend';\n\nexport default function validateLayer(options) {\n let errors = [];\n\n const layer = options.value;\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n\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\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\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\n let parent;\n\n style.layers.forEach((layer) => {\n if (unbundle(layer.id) === ref) parent = layer;\n });\n\n if (!parent) {\n errors.push(new ValidationError(key, layer.ref, `ref layer \"${ref}\" not found`));\n } else if (parent.ref) {\n errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer'));\n } else {\n type = unbundle(parent.type);\n }\n } else if (type !== 'background') {\n if (!layer.source) {\n errors.push(new ValidationError(key, layer, 'missing required property \"source\"'));\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 } else if (sourceType === 'vector' && type === 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster source`));\n } else if (sourceType === 'raster' && type !== 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a vector source`));\n } else if (sourceType === 'vector' && !layer['source-layer']) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" must specify a \"source-layer\"`));\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 } 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\n errors = errors.concat(validateObject({\n key,\n value: layer,\n valueSpec: styleSpec.layer,\n style: options.style,\n styleSpec: options.styleSpec,\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 validateSpec({\n key: `${key}.type`,\n value: layer.type,\n valueSpec: styleSpec.layer.type,\n style: options.style,\n styleSpec: options.styleSpec,\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 objectElementValidators: {\n '*'(options) {\n return validateLayoutProperty(extend({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 objectElementValidators: {\n '*'(options) {\n return validatePaintProperty(extend({layerType: type}, options));\n }\n }\n });\n }\n }\n }));\n\n return errors;\n}\n","\nimport ValidationError from '../error/validation_error';\nimport { unbundle } from '../util/unbundle_jsonlint';\nimport validateObject from './validate_object';\nimport validateEnum from './validate_enum';\nimport validateExpression from './validate_expression';\n\nexport default function validateSource(options) {\n const value = options.value;\n const key = options.key;\n const styleSpec = options.styleSpec;\n const style = options.style;\n\n if (!value.type) {\n return [new ValidationError(key, value, '\"type\" is required')];\n }\n\n const type = unbundle(value.type);\n let errors;\n\n switch (type) {\n case 'vector':\n case 'raster':\n case 'raster-dem':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec[`source_${type.replace('-', '_')}`],\n style: options.style,\n styleSpec\n });\n return errors;\n\n case 'geojson':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec.source_geojson,\n style,\n styleSpec\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\n errors.push(...validateExpression({\n key: `${key}.${prop}.map`,\n value: mapExpr,\n expressionContext: 'cluster-map'\n }));\n errors.push(...validateExpression({\n key: `${key}.${prop}.reduce`,\n value: reduceExpr,\n expressionContext: 'cluster-reduce'\n }));\n }\n }\n return errors;\n\n case 'video':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_video,\n style,\n styleSpec\n });\n\n case 'image':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_image,\n style,\n styleSpec\n });\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\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 styleSpec\n });\n }\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validate from './validate';\n\nexport default function validateLight(options) {\n const light = options.value;\n const styleSpec = options.styleSpec;\n const lightSpec = styleSpec.light;\n const style = options.style;\n\n let errors = [];\n\n const rootType = getType(light);\n if (light === undefined) {\n return errors;\n } else if (rootType !== 'object') {\n errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]);\n return errors;\n }\n\n for (const key in light) {\n const transitionMatch = key.match(/^(.*)-transition$/);\n\n if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) {\n errors = errors.concat(validate({\n key,\n value: light[key],\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n }));\n } else if (lightSpec[key]) {\n errors = errors.concat(validate({\n key,\n value: light[key],\n valueSpec: lightSpec[key],\n style,\n styleSpec\n }));\n } else {\n errors = errors.concat([new ValidationError(key, light[key], `unknown property \"${key}\"`)]);\n }\n }\n\n return errors;\n}\n","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateString(options) {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n\n if (type !== 'string') {\n return [new ValidationError(key, value, `string expected, ${type} found`)];\n }\n\n return [];\n}\n","\nimport extend from '../util/extend';\nimport { unbundle, deepUnbundle } from '../util/unbundle_jsonlint';\nimport { isExpression } from '../expression';\nimport { isFunction } from '../function';\n\nimport validateFunction from './validate_function';\nimport validateExpression from './validate_expression';\nimport validateObject from './validate_object';\nimport validateArray from './validate_array';\nimport validateBoolean from './validate_boolean';\nimport validateNumber from './validate_number';\nimport validateColor from './validate_color';\nimport validateConstants from './validate_constants';\nimport validateEnum from './validate_enum';\nimport validateFilter from './validate_filter';\nimport validateLayer from './validate_layer';\nimport validateSource from './validate_source';\nimport validateLight from './validate_light';\nimport validateString from './validate_string';\nimport validateFormatted from './validate_formatted';\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 'string': validateString,\n 'formatted': validateFormatted\n};\n\n// Main recursive validation function. Tracks:\n//\n// - key: string representing location of validation in style tree. Used only\n// for more informative error reporting.\n// - 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// - valueSpec: current spec being evaluated. Tracks value.\n// - styleSpec: current full spec being evaluated.\n\nexport default function validate(options) {\n const value = options.value;\n const valueSpec = options.valueSpec;\n const styleSpec = options.styleSpec;\n\n if (valueSpec.expression && isFunction(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(extend({}, options, {\n valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec\n }));\n return valid;\n }\n}\n","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateBoolean(options) {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n\n if (type !== 'boolean') {\n return [new ValidationError(key, value, `boolean expected, ${type} found`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport { parseCSSColor } from 'csscolorparser';\n\nexport default function validateColor(options) {\n const key = options.key;\n const value = options.value;\n const type = getType(value);\n\n if (type !== 'string') {\n return [new ValidationError(key, value, `color expected, ${type} found`)];\n }\n\n if (parseCSSColor(value) === null) {\n return [new ValidationError(key, value, `color expected, \"${value}\" found`)];\n }\n\n return [];\n}\n","// @flow\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\n\nexport default function validateFormatted(options: any) {\n if (validateString(options).length === 0) {\n return [];\n }\n\n return validateExpression(options);\n}\n","\nimport ValidationError from '../error/validation_error';\nimport validateString from './validate_string';\n\nexport default function(options) {\n const value = options.value;\n const key = options.key;\n\n const errors = validateString(options);\n if (errors.length) return errors;\n\n if (value.indexOf('{fontstack}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{fontstack}\" token'));\n }\n\n if (value.indexOf('{range}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{range}\" token'));\n }\n\n return errors;\n}\n","\nimport validateConstants from './validate/validate_constants';\nimport validate from './validate/validate';\nimport latestStyleSpec from './reference/latest';\nimport validateGlyphsURL from './validate/validate_glyphs_url';\n\nimport validateSource from './validate/validate_source';\nimport validateLight from './validate/validate_light';\nimport validateLayer from './validate/validate_layer';\nimport validateFilter from './validate/validate_filter';\nimport validatePaintProperty from './validate/validate_paint_property';\nimport validateLayoutProperty from './validate/validate_layout_property';\n\n/**\n * Validate a Mapbox GL style against the style specification. This entrypoint,\n * `mapbox-gl-style-spec/lib/validate_style.min`, is designed to produce as\n * small a browserify bundle as possible by omitting unnecessary functionality\n * and legacy style specifications.\n *\n * @private\n * @param {Object} style The style to be validated.\n * @param {Object} [styleSpec] The style specification to validate against.\n * If omitted, the latest style spec is used.\n * @returns {Array}\n * @example\n * var validate = require('mapbox-gl-style-spec/lib/validate_style.min');\n * var errors = validate(style);\n */\nfunction validateStyleMin(style, styleSpec) {\n styleSpec = styleSpec || latestStyleSpec;\n\n let errors = [];\n\n errors = errors.concat(validate({\n key: '',\n value: style,\n valueSpec: styleSpec.$root,\n styleSpec,\n style,\n objectElementValidators: {\n glyphs: validateGlyphsURL,\n '*'() {\n return [];\n }\n }\n }));\n\n if (style.constants) {\n errors = errors.concat(validateConstants({\n key: 'constants',\n value: style.constants,\n style,\n styleSpec\n }));\n }\n\n return sortErrors(errors);\n}\n\nvalidateStyleMin.source = wrapCleanErrors(validateSource);\nvalidateStyleMin.light = wrapCleanErrors(validateLight);\nvalidateStyleMin.layer = wrapCleanErrors(validateLayer);\nvalidateStyleMin.filter = wrapCleanErrors(validateFilter);\nvalidateStyleMin.paintProperty = wrapCleanErrors(validatePaintProperty);\nvalidateStyleMin.layoutProperty = wrapCleanErrors(validateLayoutProperty);\n\nfunction sortErrors(errors) {\n return [].concat(errors).sort((a, b) => {\n return a.line - b.line;\n });\n}\n\nfunction wrapCleanErrors(inner) {\n return function(...args) {\n return sortErrors(inner.apply(this, args));\n };\n}\n\nexport default validateStyleMin;\n","// @flow\nimport validateStyleMin from '../style-spec/validate_style.min';\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 = (Object) => $ReadOnlyArray;\n\ntype ValidateStyle = {\n (Object, ?Object): $ReadOnlyArray,\n source: Validator,\n layer: Validator,\n light: Validator,\n filter: Validator,\n paintProperty: Validator,\n layoutProperty: Validator\n};\n\nexport const validateStyle = (validateStyleMin: ValidateStyle);\n\nexport const validateSource = validateStyle.source;\nexport const validateLight = validateStyle.light;\nexport const validateFilter = validateStyle.filter;\nexport const validatePaintProperty = validateStyle.paintProperty;\nexport const validateLayoutProperty = validateStyle.layoutProperty;\n\nexport function emitValidationErrors(emitter: Evented, errors: ?$ReadOnlyArray<{message: string, identifier?: string}>): 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","'use strict';\n\nmodule.exports = GridIndex;\n\nvar NUM_PARAMS = 3;\n\nfunction GridIndex(extent, n, padding) {\n var cells = this.cells = [];\n\n if (extent instanceof ArrayBuffer) {\n this.arrayBuffer = extent;\n var 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 (var k = 0; k < this.d * this.d; k++) {\n var start = array[NUM_PARAMS + k];\n var end = array[NUM_PARAMS + k + 1];\n cells.push(start === end ?\n null :\n array.subarray(start, end));\n }\n var keysOffset = array[NUM_PARAMS + cells.length];\n var bboxesOffset = array[NUM_PARAMS + cells.length + 1];\n this.keys = array.subarray(keysOffset, bboxesOffset);\n this.bboxes = array.subarray(bboxesOffset);\n\n this.insert = this._insertReadonly;\n\n } else {\n this.d = n + 2 * padding;\n for (var 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 var p = (padding / n) * extent;\n this.min = -p;\n this.max = extent + p;\n}\n\n\nGridIndex.prototype.insert = function(key, x1, y1, x2, y2) {\n this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++);\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\nGridIndex.prototype._insertReadonly = function() {\n throw 'Cannot insert into a GridIndex created from an ArrayBuffer.';\n};\n\nGridIndex.prototype._insertCell = function(x1, y1, x2, y2, cellIndex, uid) {\n this.cells[cellIndex].push(uid);\n};\n\nGridIndex.prototype.query = function(x1, y1, x2, y2, intersectionTest) {\n var min = this.min;\n var 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 var result = [];\n var seenUids = {};\n this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest);\n return result;\n }\n};\n\nGridIndex.prototype._queryCell = function(x1, y1, x2, y2, cellIndex, result, seenUids, intersectionTest) {\n var cell = this.cells[cellIndex];\n if (cell !== null) {\n var keys = this.keys;\n var bboxes = this.bboxes;\n for (var u = 0; u < cell.length; u++) {\n var uid = cell[u];\n if (seenUids[uid] === undefined) {\n var 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\nGridIndex.prototype._forEachCell = function(x1, y1, x2, y2, fn, arg1, arg2, intersectionTest) {\n var cx1 = this._convertToCellCoord(x1);\n var cy1 = this._convertToCellCoord(y1);\n var cx2 = this._convertToCellCoord(x2);\n var cy2 = this._convertToCellCoord(y2);\n for (var x = cx1; x <= cx2; x++) {\n for (var y = cy1; y <= cy2; y++) {\n var 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\nGridIndex.prototype._convertFromCellCoord = function(x) {\n return (x - this.padding) / this.scale;\n};\n\nGridIndex.prototype._convertToCellCoord = function(x) {\n return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding));\n};\n\nGridIndex.prototype.toArrayBuffer = function() {\n if (this.arrayBuffer) return this.arrayBuffer;\n\n var cells = this.cells;\n\n var metadataLength = NUM_PARAMS + this.cells.length + 1 + 1;\n var totalCellLength = 0;\n for (var i = 0; i < this.cells.length; i++) {\n totalCellLength += this.cells[i].length;\n }\n\n var 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 var offset = metadataLength;\n for (var k = 0; k < cells.length; k++) {\n var 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","// @flow\n\nimport assert from 'assert';\n\nimport Grid from 'grid-index';\nimport Color from '../style-spec/util/color';\nimport { StylePropertyFunction, StyleExpression, ZoomDependentExpression, ZoomConstantExpression } from '../style-spec/expression';\nimport CompoundExpression from '../style-spec/expression/compound_expression';\nimport expressions from '../style-spec/expression/definitions';\nimport window from './window';\nconst { ImageData } = window;\n\nimport type {Transferable} from '../types/transferable';\n\ntype SerializedObject = { [string]: Serialized }; // eslint-disable-line\nexport type Serialized =\n | null\n | void\n | boolean\n | number\n | string\n | Boolean\n | Number\n | String\n | Date\n | RegExp\n | ArrayBuffer\n | $ArrayBufferView\n | ImageData\n | Array\n | SerializedObject;\n\ntype Registry = {\n [string]: {\n klass: Class,\n omit: $ReadOnlyArray,\n shallow: $ReadOnlyArray\n }\n};\n\ntype RegisterOptions = {\n omit?: $ReadOnlyArray<$Keys>,\n shallow?: $ReadOnlyArray<$Keys>\n}\n\nconst registry: Registry = {};\n\n/**\n * Register the given class as serializable.\n *\n * @param options\n * @param options.omit List of properties to omit from serialization (e.g., cached/computed properties)\n * @param options.shallow List of properties that should be serialized by a simple shallow copy, rather than by a recursive call to serialize().\n *\n * @private\n */\nexport function register(name: string, klass: Class, options: RegisterOptions = {}) {\n assert(!registry[name], `${name} is already registered.`);\n (Object.defineProperty: any)(klass, '_classRegistryKey', {\n value: name,\n writeable: false\n });\n registry[name] = {\n klass,\n omit: options.omit || [],\n shallow: options.shallow || []\n };\n}\n\nregister('Object', Object);\n\ntype SerializedGrid = { buffer: ArrayBuffer };\n\nGrid.serialize = function serialize(grid: Grid, transferables?: Array): SerializedGrid {\n const buffer = grid.toArrayBuffer();\n if (transferables) {\n transferables.push(buffer);\n }\n return {buffer};\n};\n\nGrid.deserialize = function deserialize(serialized: SerializedGrid): Grid {\n return new Grid(serialized.buffer);\n};\nregister('Grid', Grid);\n\nregister('Color', Color);\nregister('Error', Error);\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]: any)._classRegistryKey) continue;\n register(`Expression_${name}`, expressions[name]);\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 *\n * @private\n */\nexport function serialize(input: mixed, transferables?: Array): Serialized {\n if (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 return input;\n }\n\n if (input instanceof ArrayBuffer) {\n if (transferables) {\n transferables.push(input);\n }\n return input;\n }\n\n if (ArrayBuffer.isView(input)) {\n const view: $ArrayBufferView = (input: any);\n if (transferables) {\n transferables.push(view.buffer);\n }\n return view;\n }\n\n if (input instanceof ImageData) {\n if (transferables) {\n transferables.push(input.data.buffer);\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 const klass = (input.constructor: any);\n const name = klass._classRegistryKey;\n if (!name) {\n throw new Error(`can't serialize object of unregistered class`);\n }\n assert(registry[name]);\n\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): SerializedObject) : {};\n\n if (!klass.serialize) {\n for (const key in input) {\n // any cast due to https://github.com/facebook/flow/issues/5393\n if (!(input: any).hasOwnProperty(key)) continue;\n if (registry[name].omit.indexOf(key) >= 0) continue;\n const property = (input: any)[key];\n properties[key] = registry[name].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 // make sure statically serialized object survives transfer of $name property\n assert(!transferables || properties !== transferables[transferables.length - 1]);\n }\n\n if (properties.$name) {\n throw new Error('$name property is reserved for worker serialization logic.');\n }\n if (name !== 'Object') {\n properties.$name = name;\n }\n\n return properties;\n }\n\n throw new Error(`can't serialize object of type ${typeof input}`);\n}\n\nexport function deserialize(input: Serialized): mixed {\n if (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 ArrayBuffer ||\n ArrayBuffer.isView(input) ||\n input instanceof ImageData) {\n return input;\n }\n\n if (Array.isArray(input)) {\n return input.map(deserialize);\n }\n\n if (typeof input === 'object') {\n const name = (input: any).$name || 'Object';\n\n const {klass} = registry[name];\n if (!klass) {\n throw new Error(`can't deserialize unregistered class ${name}`);\n }\n\n if (klass.deserialize) {\n return (klass.deserialize: typeof 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: SerializedObject)[key];\n result[key] = registry[name].shallow.indexOf(key) >= 0 ? value : deserialize(value);\n }\n\n return result;\n }\n\n throw new Error(`can't deserialize object of type ${typeof input}`);\n}\n","// @flow\n\nclass 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\nexport default ZoomHistory;\n","// @flow\n\n// The following table comes from .\n// Keep it synchronized with .\n\ntype UnicodeBlockLookup = {[key: string]: (char: number) => boolean};\n\nconst 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-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 // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F,\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 // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F,\n // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F,\n // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F,\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 // '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 // 'Ahom': (char) => char >= 0x11700 && char <= 0x1173F,\n // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F,\n // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF,\n // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF,\n // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F,\n // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF,\n // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF,\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 // '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 // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F,\n // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1343F,\n // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F,\n // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F,\n // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F,\n // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF,\n // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F,\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 // '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 // '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 // '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 // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F,\n // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F,\n // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF,\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 // '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 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\nexport default unicodeBlockLookup;\n","// @flow\n\n/* eslint-disable new-cap */\n\nimport 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\nexport function charAllowsLetterSpacing(char: number) {\n if (isChar['Arabic'](char)) return false;\n if (isChar['Arabic Supplement'](char)) return false;\n if (isChar['Arabic Extended-A'](char)) return false;\n if (isChar['Arabic Presentation Forms-A'](char)) return false;\n if (isChar['Arabic Presentation Forms-B'](char)) return false;\n\n return true;\n}\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['Bopomofo Extended'](char)) return true;\n if (isChar['Bopomofo'](char)) return true;\n if (isChar['CJK Compatibility Forms'](char)) return true;\n if (isChar['CJK Compatibility Ideographs'](char)) return true;\n if (isChar['CJK Compatibility'](char)) return true;\n if (isChar['CJK Radicals Supplement'](char)) return true;\n if (isChar['CJK Strokes'](char)) return true;\n if (isChar['CJK Symbols and Punctuation'](char)) return true;\n if (isChar['CJK Unified Ideographs Extension A'](char)) return true;\n if (isChar['CJK Unified Ideographs'](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['Hiragana'](char)) return true;\n if (isChar['Ideographic Description Characters'](char)) return true;\n if (isChar['Kangxi Radicals'](char)) return true;\n if (isChar['Katakana Phonetic Extensions'](char)) return true;\n if (isChar['Katakana'](char)) return true;\n if (isChar['Vertical Forms'](char)) return true;\n if (isChar['Yi Radicals'](char)) return true;\n if (isChar['Yi Syllables'](char)) return true;\n\n return false;\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 * @private\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['Bopomofo Extended'](char)) return true;\n if (isChar['Bopomofo'](char)) return true;\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 Ideographs'](char)) return true;\n if (isChar['CJK Compatibility'](char)) return true;\n if (isChar['CJK Radicals Supplement'](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['CJK Unified Ideographs Extension A'](char)) return true;\n if (isChar['CJK Unified Ideographs'](char)) return true;\n if (isChar['Enclosed CJK Letters and Months'](char)) return true;\n if (isChar['Hangul Compatibility Jamo'](char)) return true;\n if (isChar['Hangul Jamo Extended-A'](char)) return true;\n if (isChar['Hangul Jamo Extended-B'](char)) return true;\n if (isChar['Hangul Jamo'](char)) return true;\n if (isChar['Hangul Syllables'](char)) return true;\n if (isChar['Hiragana'](char)) return true;\n if (isChar['Ideographic Description Characters'](char)) return true;\n if (isChar['Kanbun'](char)) return true;\n if (isChar['Kangxi Radicals'](char)) return true;\n if (isChar['Katakana Phonetic Extensions'](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['Unified Canadian Aboriginal Syllabics'](char)) return true;\n if (isChar['Unified Canadian Aboriginal Syllabics Extended'](char)) return true;\n if (isChar['Vertical Forms'](char)) return true;\n if (isChar['Yijing Hexagram Symbols'](char)) return true;\n if (isChar['Yi Syllables'](char)) return true;\n if (isChar['Yi Radicals'](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 verticlly 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 * @private\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 * @private\n */\nexport function charHasRotatedVerticalOrientation(char: number) {\n return !(charHasUprightVerticalOrientation(char) ||\n charHasNeutralVerticalOrientation(char));\n}\n\nexport function charInComplexShapingScript(char: number) {\n return isChar['Arabic'](char) ||\n isChar['Arabic Supplement'](char) ||\n isChar['Arabic Extended-A'](char) ||\n isChar['Arabic Presentation Forms-A'](char) ||\n isChar['Arabic Presentation Forms-B'](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 &&\n ((char >= 0x0590 && char <= 0x08FF) ||\n isChar['Arabic Presentation Forms-A'](char) ||\n isChar['Arabic Presentation Forms-B'](char))) {\n // Main blocks for Hebrew, Arabic, Thaana and other RTL scripts\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 // http://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 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","// @flow\n\nimport { Event, Evented } from '../util/evented';\nimport browser from '../util/browser';\n\nlet pluginRequested = false;\nlet pluginURL = null;\nlet foregroundLoadComplete = false;\n\nexport const evented = new Evented();\n\ntype CompletionCallback = (error?: Error) => void;\ntype ErrorCallback = (error: Error) => void;\n\nlet _completionCallback;\n\nexport const registerForPluginAvailability = function(\n callback: (args: {pluginURL: string, completionCallback: CompletionCallback}) => void\n) {\n if (pluginURL) {\n callback({ pluginURL, completionCallback: _completionCallback});\n } else {\n evented.once('pluginAvailable', callback);\n }\n return callback;\n};\n\nexport const clearRTLTextPlugin = function() {\n pluginRequested = false;\n pluginURL = null;\n};\n\nexport const setRTLTextPlugin = function(url: string, callback: ErrorCallback) {\n if (pluginRequested) {\n throw new Error('setRTLTextPlugin cannot be called multiple times.');\n }\n pluginRequested = true;\n pluginURL = browser.resolveURL(url);\n _completionCallback = (error?: Error) => {\n if (error) {\n // Clear loaded state to allow retries\n clearRTLTextPlugin();\n if (callback) {\n callback(error);\n }\n } else {\n // Called once for each worker\n foregroundLoadComplete = true;\n }\n };\n evented.fire(new Event('pluginAvailable', { pluginURL, completionCallback: _completionCallback }));\n};\n\nexport const plugin: {\n applyArabicShaping: ?Function,\n processBidirectionalText: ?(string, Array) => Array,\n processStyledBidirectionalText: ?(string, Array, Array) => Array<[string, Array]>,\n isLoaded: () => boolean\n} = {\n applyArabicShaping: null,\n processBidirectionalText: null,\n processStyledBidirectionalText: null,\n isLoaded() {\n return foregroundLoadComplete || // Foreground: loaded if the completion callback returned successfully\n plugin.applyArabicShaping != null; // Background: loaded if the plugin functions have been compiled\n }\n};\n","// @flow\n\nimport ZoomHistory from './zoom_history';\nimport {isStringInSupportedScript} from '../util/script_detection';\nimport {plugin as rtlTextPlugin} from '../source/rtl_text_plugin';\n\nimport type {TransitionSpecification} from '../style-spec/types';\n\nexport type CrossfadeParameters = {\n fromScale: number,\n toScale: number,\n t: number\n};\n\nclass 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?: *) {\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, rtlTextPlugin.isLoaded());\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\nexport default EvaluationParameters;\n","// @flow\n\nimport assert from 'assert';\n\nimport { clone, extend, easeCubicInOut } from '../util/util';\nimport * as interpolate from '../style-spec/util/interpolate';\nimport { normalizePropertyExpression } from '../style-spec/expression';\nimport Color from '../style-spec/util/color';\nimport { register } from '../util/web_worker_transfer';\nimport EvaluationParameters from './evaluation_parameters';\n\nimport type {StylePropertySpecification} from '../style-spec/style-spec';\nimport type {\n TransitionSpecification,\n PropertyValueSpecification\n} from '../style-spec/types';\n\nimport type {\n Feature,\n FeatureState,\n StylePropertyExpression,\n SourceExpression,\n CompositeExpression\n} from '../style-spec/expression';\n\ntype TimePoint = number;\n\nexport type CrossFaded = {\n to: T,\n from: T\n};\n\n/**\n * Implements a number of classes that define state and behavior for paint and layout properties, most\n * importantly their respective evaluation chains:\n *\n * Transitionable paint property value\n * → Transitioning paint property value\n * → Possibly evaluated paint property value\n * → Fully evaluated paint property value\n *\n * Layout property value\n * → Possibly evaluated layout property value\n * → Fully evaluated layout property value\n *\n * @module\n * @private\n */\n\n/**\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 *\n * @private\n */\nexport interface Property {\n specification: StylePropertySpecification;\n possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters): R;\n interpolate(a: R, b: R, t: number): R;\n}\n\n/**\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 *\n * @private\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(parameters: EvaluationParameters): R {\n return this.property.possiblyEvaluate(this, parameters);\n }\n}\n\n// ------- Transitionable -------\n\nexport type TransitionParameters = {\n now: TimePoint,\n transition: TransitionSpecification\n};\n\n/**\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 *\n * @private\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,\n prior: TransitioningPropertyValue): TransitioningPropertyValue {\n return new TransitioningPropertyValue(this.property, this.value, prior, // eslint-disable-line no-use-before-define\n extend({}, parameters.transition, this.transition), parameters.now);\n }\n\n untransitioned(): TransitioningPropertyValue {\n return new TransitioningPropertyValue(this.property, this.value, null, {}, 0); // eslint-disable-line no-use-before-define\n }\n}\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property`, it calculates\n * an object type with the same keys and values of type `TransitionablePropertyValue`.\n *\n * @private\n */\ntype TransitionablePropertyValues\n = $Exact<$ObjMap(p: Property) => TransitionablePropertyValue>>\n\n/**\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 *\n * @private\n */\nexport class Transitionable {\n _properties: Properties;\n _values: TransitionablePropertyValues;\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitionablePropertyValues): 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 (!this._values.hasOwnProperty(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 (!this._values.hasOwnProperty(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);\n if (value !== undefined) {\n result[property] = value;\n }\n\n const transition = this.getTransition(property);\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); // eslint-disable-line no-use-before-define\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); // eslint-disable-line no-use-before-define\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// ------- Transitioning -------\n\n/**\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 *\n * @private\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(parameters: EvaluationParameters): R {\n const now = parameters.now || 0;\n const finalValue = this.value.possiblyEvaluate(parameters);\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);\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), finalValue, easeCubicInOut(t));\n }\n }\n}\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property`, it calculates\n * an object type with the same keys and values of type `TransitioningPropertyValue`.\n *\n * @private\n */\ntype TransitioningPropertyValues\n = $Exact<$ObjMap(p: Property) => TransitioningPropertyValue>>\n\n/**\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 *\n * @private\n */\nexport class Transitioning {\n _properties: Properties;\n _values: TransitioningPropertyValues;\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitioningPropertyValues): any);\n }\n\n possiblyEvaluate(parameters: EvaluationParameters): PossiblyEvaluated {\n const result = new PossiblyEvaluated(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].possiblyEvaluate(parameters);\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 * A helper type: given an object type `Properties` whose values are each of type `Property`, it calculates\n * an object type with the same keys and values of type `PropertyValue`.\n *\n * @private\n */\ntype PropertyValues\n = $Exact<$ObjMap(p: Property) => PropertyValue>>\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 *\n * @private\n */\nexport class Layout {\n _properties: Properties;\n _values: PropertyValues;\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultPropertyValues): any);\n }\n\n getValue(name: S) {\n return clone(this._values[name].value);\n }\n\n setValue(name: S, value: *) {\n this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value));\n }\n\n serialize() {\n const result: any = {};\n for (const property of Object.keys(this._values)) {\n const value = this.getValue(property);\n if (value !== undefined) {\n result[property] = value;\n }\n }\n return result;\n }\n\n possiblyEvaluate(parameters: EvaluationParameters): PossiblyEvaluated {\n const result = new PossiblyEvaluated(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].possiblyEvaluate(parameters);\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 *\n * @private\n */\ntype PossiblyEvaluatedValue =\n | {kind: 'constant', value: T}\n | SourceExpression\n | CompositeExpression;\n\n/**\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 *\n * @private\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(feature: Feature, featureState: FeatureState): T {\n return this.property.evaluate(this.value, this.parameters, feature, featureState);\n }\n}\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property`, it calculates\n * an object type with the same keys, and values of type `R`.\n *\n * For properties that don't allow data-driven values, `R` is a scalar type such as `number`, `string`, or `Color`.\n * For data-driven properties, it is `PossiblyEvaluatedPropertyValue`. Critically, the type definitions are set up\n * in a way that allows flow to know which of these two cases applies for any given property name, and if you attempt\n * to use a `PossiblyEvaluatedPropertyValue` as if it was a scalar, or vice versa, you will get a type error. (However,\n * there's at least one case in which flow fails to produce a type error that you should be aware of: in a context such\n * as `layer.paint.get('foo-opacity') === 0`, if `foo-opacity` is data-driven, than the left-hand side is of type\n * `PossiblyEvaluatedPropertyValue`, but flow will not complain about comparing this to a number using `===`.\n * See https://github.com/facebook/flow/issues/2359.)\n *\n * There's also a third, special case possiblity for `R`: for cross-faded properties, it's `?CrossFaded`.\n *\n * @private\n */\ntype PossiblyEvaluatedPropertyValues\n = $Exact<$ObjMap(p: Property) => R>>\n\n/**\n * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a\n * given layer type.\n * @private\n */\nexport class PossiblyEvaluated {\n _properties: Properties;\n _values: PossiblyEvaluatedPropertyValues;\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultPossiblyEvaluatedValues): any);\n }\n\n get(name: S): $ElementType, S> {\n return this._values[name];\n }\n}\n\n/**\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 *\n * @private\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 assert(!value.isDataDriven());\n return value.expression.evaluate(parameters);\n }\n\n interpolate(a: T, b: T, t: number): T {\n const interp: ?(a: T, b: T, t: number) => T = (interpolate: any)[this.specification.type];\n if (interp) {\n return interp(a, b, t);\n } else {\n return a;\n }\n }\n}\n\n/**\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 *\n * @private\n */\nexport class DataDrivenProperty implements Property> {\n specification: StylePropertySpecification;\n overrides: ?Object;\n\n constructor(specification: StylePropertySpecification, overrides?: Object) {\n this.specification = specification;\n this.overrides = overrides;\n }\n\n possiblyEvaluate(value: PropertyValue>, parameters: EvaluationParameters): PossiblyEvaluatedPropertyValue {\n if (value.expression.kind === 'constant' || value.expression.kind === 'camera') {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: value.expression.evaluate(parameters)}, parameters);\n } else {\n return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);\n }\n }\n\n interpolate(a: PossiblyEvaluatedPropertyValue,\n b: PossiblyEvaluatedPropertyValue,\n t: number): 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: any)}, a.parameters);\n }\n\n const interp: ?(a: T, b: T, t: number) => T = (interpolate: any)[this.specification.type];\n if (interp) {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: interp(a.value.value, b.value.value, t)}, a.parameters);\n } else {\n return a;\n }\n }\n\n evaluate(value: PossiblyEvaluatedValue, parameters: EvaluationParameters, feature: Feature, featureState: FeatureState): T {\n if (value.kind === 'constant') {\n return value.value;\n } else {\n return value.evaluate(parameters, feature, featureState);\n }\n }\n}\n\n/**\n * An implementation of `Property` for data driven `line-pattern` which are transitioned by cross-fading\n * rather than interpolation.\n *\n * @private\n */\n\nexport class CrossFadedDataDrivenProperty extends DataDrivenProperty> {\n\n possiblyEvaluate(value: PropertyValue, PossiblyEvaluatedPropertyValue>>, parameters: EvaluationParameters): 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 constantValue = value.expression.evaluate(parameters);\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(value: PossiblyEvaluatedValue>, globals: EvaluationParameters, feature: Feature, featureState: FeatureState): ?CrossFaded {\n if (value.kind === 'source') {\n const constant = value.evaluate(globals, feature, featureState);\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 * An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading\n * rather than interpolation.\n *\n * @private\n */\nexport class CrossFadedProperty implements Property> {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue>, parameters: EvaluationParameters): ?CrossFaded {\n if (value.value === undefined) {\n return undefined;\n } else if (value.expression.kind === 'constant') {\n const constant = value.expression.evaluate(parameters);\n return this._calculate(constant, constant, constant, parameters);\n } else {\n assert(!value.isDataDriven());\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): ?CrossFaded {\n return a;\n }\n}\n\n/**\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 * @private\n */\n\nexport class ColorRampProperty implements Property {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters): boolean {\n return !!value.expression.evaluate(parameters);\n }\n\n interpolate(): boolean { return false; }\n}\n\n/**\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 *\n * @private\n */\nexport class Properties {\n properties: Props;\n defaultPropertyValues: PropertyValues;\n defaultTransitionablePropertyValues: TransitionablePropertyValues;\n defaultTransitioningPropertyValues: TransitioningPropertyValues;\n defaultPossiblyEvaluatedValues: PossiblyEvaluatedPropertyValues;\n overridableProperties: Array;\n\n constructor(properties: Props) {\n this.properties = properties;\n this.defaultPropertyValues = ({}: any);\n this.defaultTransitionablePropertyValues = ({}: any);\n this.defaultTransitioningPropertyValues = ({}: any);\n this.defaultPossiblyEvaluatedValues = ({}: any);\n this.overridableProperties = ([]: any);\n\n for (const property in properties) {\n const prop = properties[property];\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(({}: any));\n }\n }\n}\n\nregister('DataDrivenProperty', DataDrivenProperty);\nregister('DataConstantProperty', DataConstantProperty);\nregister('CrossFadedDataDrivenProperty', CrossFadedDataDrivenProperty);\nregister('CrossFadedProperty', CrossFadedProperty);\nregister('ColorRampProperty', ColorRampProperty);\n","// @flow\n\nimport { endsWith, filterObject } from '../util/util';\n\nimport styleSpec from '../style-spec/reference/latest';\nimport {\n validateStyle,\n validateLayoutProperty,\n validatePaintProperty,\n emitValidationErrors\n} from './validate_style';\nimport { Evented } from '../util/evented';\nimport { Layout, Transitionable, Transitioning, Properties, PossiblyEvaluatedPropertyValue } from './properties';\nimport { supportsPropertyExpression } from '../style-spec/util/properties';\n\nimport type { FeatureState } from '../style-spec/expression';\nimport type {Bucket} from '../data/bucket';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureFilter} from '../style-spec/feature_filter';\nimport type {TransitionParameters, PropertyValue} from './properties';\nimport type EvaluationParameters, {CrossfadeParameters} from './evaluation_parameters';\nimport type Transform from '../geo/transform';\nimport type {\n LayerSpecification,\n FilterSpecification\n} from '../style-spec/types';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer';\nimport type Map from '../ui/map';\nimport type {StyleSetterOptions} from './style';\n\nconst TRANSITION_SUFFIX = '-transition';\n\nclass StyleLayer extends Evented {\n id: string;\n metadata: mixed;\n type: string;\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 +layout: mixed;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n +paint: mixed;\n\n _featureFilter: FeatureFilter;\n\n +queryRadius: (bucket: Bucket) => number;\n +queryIntersectsFeature: (queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number,\n pixelPosMatrix: Float32Array) => boolean | number;\n\n +onAdd: ?(map: Map) => void;\n +onRemove: ?(map: Map) => void;\n\n constructor(layer: LayerSpecification | CustomLayerInterface, properties: $ReadOnly<{layout?: Properties<*>, paint?: Properties<*>}>) {\n super();\n\n this.id = layer.id;\n this.type = layer.type;\n this._featureFilter = () => true;\n\n if (layer.type === 'custom') return;\n\n layer = ((layer: any): 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 }\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 (endsWith(name, 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: mixed, 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 (endsWith(name, TRANSITION_SUFFIX)) {\n this._transitionablePaint.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), (value: 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 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) {\n if (parameters.getCrossfadeParameters) {\n this._crossfadeParameters = parameters.getCrossfadeParameters();\n }\n\n if (this._unevaluatedLayout) {\n (this: any).layout = this._unevaluatedLayout.possiblyEvaluate(parameters);\n }\n\n (this: any).paint = this._transitioningPaint.possiblyEvaluate(parameters);\n }\n\n serialize() {\n const output: any = {\n 'id': this.id,\n 'type': this.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,\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: mixed, 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: any).paint._values) {\n const value = (this: 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\nexport default StyleLayer;\n","// @flow\n\n// Note: all \"sizes\" are measured in bytes\n\nimport assert from 'assert';\n\nimport type {Transferable} from '../types/transferable';\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\nexport type ViewType = $Keys;\n\n/**\n * @private\n */\nclass Struct {\n _pos1: number;\n _pos2: number;\n _pos4: number;\n _pos8: number;\n +_structArray: StructArray;\n\n // The following properties are defined on the prototype of sub classes.\n size: number;\n\n /**\n * @param {StructArray} structArray The StructArray the struct is stored in\n * @param {number} index The index of the struct in the StructArray.\n * @private\n */\n constructor(structArray: StructArray, index: number) {\n (this: 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\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\nexport type SerializedStructArray = {\n length: number,\n arrayBuffer: ArrayBuffer\n};\n\n/**\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 corrseponding 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 convience of working with (seemingly) plain\n * Javascript objects without the overhead of serializing/deserializing them\n * into ArrayBuffers for efficient web worker transfer.\n *\n * @private\n */\nclass 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 +emplaceBack: Function;\n +emplace: Function;\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 assert(!array.isTransferred);\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 the length of the array to 0 without de-allocating capcacity.\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 {number} n The new size of the array.\n */\n resize(n: number) {\n assert(!this.isTransferred);\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 {number} 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 *\n * @private\n */\nfunction createLayout(\n members: Array<{ name: string, type: ViewType, +components?: number, }>,\n alignment: number = 1\n): StructArrayLayout {\n\n let offset = 0;\n let maxSize = 0;\n const layoutMembers = members.map((member) => {\n assert(member.name.length);\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.js, then run `yarn run codegen`.\n// @flow\n\nimport assert from 'assert';\nimport {Struct, StructArray} from '../util/struct_array';\nimport {register} from '../util/web_worker_transfer';\nimport Point from '@mapbox/point-geometry';\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[2]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Int16[4]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Int16[2]\n * [4]: Int16[4]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Int16[2]\n * [4]: Uint8[4]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Uint16[8]\n *\n * @private\n */\nclass StructArrayLayout8ui16 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 emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number) {\n const o2 = i * 8;\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 return i;\n }\n}\n\nStructArrayLayout8ui16.prototype.bytesPerElement = 16;\nregister('StructArrayLayout8ui16', StructArrayLayout8ui16);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[4]\n * [8]: Uint16[4]\n *\n * @private\n */\nclass StructArrayLayout4i4ui16 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 emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number) {\n const o2 = i * 8;\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 return i;\n }\n}\n\nStructArrayLayout4i4ui16.prototype.bytesPerElement = 16;\nregister('StructArrayLayout4i4ui16', StructArrayLayout4i4ui16);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Float32[3]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Uint32[1]\n *\n * @private\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 emplaceBack(v0: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n 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 * Implementation of the StructArray layout:\n * [0]: Int16[6]\n * [12]: Uint32[1]\n * [16]: Uint16[2]\n * [20]: Int16[2]\n *\n * @private\n */\nclass StructArrayLayout6i1ul2ui2i24 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 emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: 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);\n }\n\n 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) {\n const o2 = i * 12;\n const o4 = 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 this.uint32[o4 + 3] = v6;\n this.uint16[o2 + 8] = v7;\n this.uint16[o2 + 9] = v8;\n this.int16[o2 + 10] = v9;\n this.int16[o2 + 11] = v10;\n return i;\n }\n}\n\nStructArrayLayout6i1ul2ui2i24.prototype.bytesPerElement = 24;\nregister('StructArrayLayout6i1ul2ui2i24', StructArrayLayout6i1ul2ui2i24);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[2]\n * [4]: Int16[2]\n * [8]: Int16[2]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Uint8[2]\n * [4]: Float32[2]\n *\n * @private\n */\nclass StructArrayLayout2ub2f12 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 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 emplace(i: number, v0: number, v1: number, v2: number, v3: number) {\n const o1 = i * 12;\n const o4 = i * 3;\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 return i;\n }\n}\n\nStructArrayLayout2ub2f12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout2ub2f12', StructArrayLayout2ub2f12);\n\n/**\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 *\n * @private\n */\nclass StructArrayLayout2i2ui3ul3ui2f3ub1ul44 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 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) {\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);\n }\n\n 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) {\n const o2 = i * 22;\n const o4 = i * 11;\n const o1 = i * 44;\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 return i;\n }\n}\n\nStructArrayLayout2i2ui3ul3ui2f3ub1ul44.prototype.bytesPerElement = 44;\nregister('StructArrayLayout2i2ui3ul3ui2f3ub1ul44', StructArrayLayout2i2ui3ul3ui2f3ub1ul44);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[6]\n * [12]: Uint16[11]\n * [36]: Uint32[1]\n * [40]: Float32[2]\n *\n * @private\n */\nclass StructArrayLayout6i11ui1ul2f48 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 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) {\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);\n }\n\n 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) {\n const o2 = i * 24;\n const o4 = 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.int16[o2 + 4] = v4;\n this.int16[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 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.uint32[o4 + 9] = v17;\n this.float32[o4 + 10] = v18;\n this.float32[o4 + 11] = v19;\n return i;\n }\n}\n\nStructArrayLayout6i11ui1ul2f48.prototype.bytesPerElement = 48;\nregister('StructArrayLayout6i11ui1ul2f48', StructArrayLayout6i11ui1ul2f48);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Float32[1]\n *\n * @private\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 emplaceBack(v0: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n 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 * Implementation of the StructArray layout:\n * [0]: Int16[3]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Uint32[1]\n * [4]: Uint16[2]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Uint16[3]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Uint16[2]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Uint16[1]\n *\n * @private\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 emplaceBack(v0: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n 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 * Implementation of the StructArray layout:\n * [0]: Float32[2]\n *\n * @private\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 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 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 * Implementation of the StructArray layout:\n * [0]: Float32[4]\n *\n * @private\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 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 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\nclass CollisionBoxStruct extends Struct {\n _structArray: CollisionBoxArray;\n anchorPointX: number;\n anchorPointY: number;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n featureIndex: number;\n sourceLayerIndex: number;\n bucketIndex: number;\n radius: number;\n signedDistanceFromAnchor: number;\n anchorPoint: Point;\n get anchorPointX() { return this._structArray.int16[this._pos2 + 0]; }\n set anchorPointX(x: number) { this._structArray.int16[this._pos2 + 0] = x; }\n get anchorPointY() { return this._structArray.int16[this._pos2 + 1]; }\n set anchorPointY(x: number) { this._structArray.int16[this._pos2 + 1] = x; }\n get x1() { return this._structArray.int16[this._pos2 + 2]; }\n set x1(x: number) { this._structArray.int16[this._pos2 + 2] = x; }\n get y1() { return this._structArray.int16[this._pos2 + 3]; }\n set y1(x: number) { this._structArray.int16[this._pos2 + 3] = x; }\n get x2() { return this._structArray.int16[this._pos2 + 4]; }\n set x2(x: number) { this._structArray.int16[this._pos2 + 4] = x; }\n get y2() { return this._structArray.int16[this._pos2 + 5]; }\n set y2(x: number) { this._structArray.int16[this._pos2 + 5] = x; }\n get featureIndex() { return this._structArray.uint32[this._pos4 + 3]; }\n set featureIndex(x: number) { this._structArray.uint32[this._pos4 + 3] = x; }\n get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 8]; }\n set sourceLayerIndex(x: number) { this._structArray.uint16[this._pos2 + 8] = x; }\n get bucketIndex() { return this._structArray.uint16[this._pos2 + 9]; }\n set bucketIndex(x: number) { this._structArray.uint16[this._pos2 + 9] = x; }\n get radius() { return this._structArray.int16[this._pos2 + 10]; }\n set radius(x: number) { this._structArray.int16[this._pos2 + 10] = x; }\n get signedDistanceFromAnchor() { return this._structArray.int16[this._pos2 + 11]; }\n set signedDistanceFromAnchor(x: number) { this._structArray.int16[this._pos2 + 11] = x; }\n get anchorPoint() { return new Point(this.anchorPointX, this.anchorPointY); }\n}\n\nCollisionBoxStruct.prototype.size = 24;\n\nexport type CollisionBox = CollisionBoxStruct;\n\n/**\n * @private\n */\nexport class CollisionBoxArray extends StructArrayLayout6i1ul2ui2i24 {\n /**\n * Return the CollisionBoxStruct at the given location in the array.\n * @param {number} index The index of the element.\n */\n get(index: number): CollisionBoxStruct {\n assert(!this.isTransferred);\n return new CollisionBoxStruct(this, index);\n }\n}\n\nregister('CollisionBoxArray', CollisionBoxArray);\n\nclass PlacedSymbolStruct extends Struct {\n _structArray: PlacedSymbolArray;\n anchorX: number;\n anchorY: number;\n glyphStartIndex: number;\n numGlyphs: number;\n vertexStartIndex: number;\n lineStartIndex: number;\n lineLength: number;\n segment: number;\n lowerSize: number;\n upperSize: number;\n lineOffsetX: number;\n lineOffsetY: number;\n writingMode: number;\n placedOrientation: number;\n hidden: number;\n crossTileID: number;\n get anchorX() { return this._structArray.int16[this._pos2 + 0]; }\n set anchorX(x: number) { this._structArray.int16[this._pos2 + 0] = x; }\n get anchorY() { return this._structArray.int16[this._pos2 + 1]; }\n set anchorY(x: number) { this._structArray.int16[this._pos2 + 1] = x; }\n get glyphStartIndex() { return this._structArray.uint16[this._pos2 + 2]; }\n set glyphStartIndex(x: number) { this._structArray.uint16[this._pos2 + 2] = x; }\n get numGlyphs() { return this._structArray.uint16[this._pos2 + 3]; }\n set numGlyphs(x: number) { this._structArray.uint16[this._pos2 + 3] = x; }\n get vertexStartIndex() { return this._structArray.uint32[this._pos4 + 2]; }\n set vertexStartIndex(x: number) { this._structArray.uint32[this._pos4 + 2] = x; }\n get lineStartIndex() { return this._structArray.uint32[this._pos4 + 3]; }\n set lineStartIndex(x: number) { this._structArray.uint32[this._pos4 + 3] = x; }\n get lineLength() { return this._structArray.uint32[this._pos4 + 4]; }\n set lineLength(x: number) { this._structArray.uint32[this._pos4 + 4] = x; }\n get segment() { return this._structArray.uint16[this._pos2 + 10]; }\n set segment(x: number) { this._structArray.uint16[this._pos2 + 10] = x; }\n get lowerSize() { return this._structArray.uint16[this._pos2 + 11]; }\n set lowerSize(x: number) { this._structArray.uint16[this._pos2 + 11] = x; }\n get upperSize() { return this._structArray.uint16[this._pos2 + 12]; }\n set upperSize(x: number) { this._structArray.uint16[this._pos2 + 12] = x; }\n get lineOffsetX() { return this._structArray.float32[this._pos4 + 7]; }\n set lineOffsetX(x: number) { this._structArray.float32[this._pos4 + 7] = x; }\n get lineOffsetY() { return this._structArray.float32[this._pos4 + 8]; }\n set lineOffsetY(x: number) { this._structArray.float32[this._pos4 + 8] = x; }\n get writingMode() { return this._structArray.uint8[this._pos1 + 36]; }\n set writingMode(x: number) { this._structArray.uint8[this._pos1 + 36] = x; }\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}\n\nPlacedSymbolStruct.prototype.size = 44;\n\nexport type PlacedSymbol = PlacedSymbolStruct;\n\n/**\n * @private\n */\nexport class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul44 {\n /**\n * Return the PlacedSymbolStruct at the given location in the array.\n * @param {number} index The index of the element.\n */\n get(index: number): PlacedSymbolStruct {\n assert(!this.isTransferred);\n return new PlacedSymbolStruct(this, index);\n }\n}\n\nregister('PlacedSymbolArray', PlacedSymbolArray);\n\nclass SymbolInstanceStruct extends Struct {\n _structArray: SymbolInstanceArray;\n anchorX: number;\n anchorY: number;\n rightJustifiedTextSymbolIndex: number;\n centerJustifiedTextSymbolIndex: number;\n leftJustifiedTextSymbolIndex: number;\n verticalPlacedTextSymbolIndex: number;\n key: number;\n textBoxStartIndex: number;\n textBoxEndIndex: number;\n verticalTextBoxStartIndex: number;\n verticalTextBoxEndIndex: number;\n iconBoxStartIndex: number;\n iconBoxEndIndex: number;\n featureIndex: number;\n numHorizontalGlyphVertices: number;\n numVerticalGlyphVertices: number;\n numIconVertices: number;\n crossTileID: number;\n textBoxScale: number;\n radialTextOffset: number;\n get anchorX() { return this._structArray.int16[this._pos2 + 0]; }\n set anchorX(x: number) { this._structArray.int16[this._pos2 + 0] = x; }\n get anchorY() { return this._structArray.int16[this._pos2 + 1]; }\n set anchorY(x: number) { this._structArray.int16[this._pos2 + 1] = x; }\n get rightJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 2]; }\n set rightJustifiedTextSymbolIndex(x: number) { this._structArray.int16[this._pos2 + 2] = x; }\n get centerJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 3]; }\n set centerJustifiedTextSymbolIndex(x: number) { this._structArray.int16[this._pos2 + 3] = x; }\n get leftJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 4]; }\n set leftJustifiedTextSymbolIndex(x: number) { this._structArray.int16[this._pos2 + 4] = x; }\n get verticalPlacedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 5]; }\n set verticalPlacedTextSymbolIndex(x: number) { this._structArray.int16[this._pos2 + 5] = x; }\n get key() { return this._structArray.uint16[this._pos2 + 6]; }\n set key(x: number) { this._structArray.uint16[this._pos2 + 6] = x; }\n get textBoxStartIndex() { return this._structArray.uint16[this._pos2 + 7]; }\n set textBoxStartIndex(x: number) { this._structArray.uint16[this._pos2 + 7] = x; }\n get textBoxEndIndex() { return this._structArray.uint16[this._pos2 + 8]; }\n set textBoxEndIndex(x: number) { this._structArray.uint16[this._pos2 + 8] = x; }\n get verticalTextBoxStartIndex() { return this._structArray.uint16[this._pos2 + 9]; }\n set verticalTextBoxStartIndex(x: number) { this._structArray.uint16[this._pos2 + 9] = x; }\n get verticalTextBoxEndIndex() { return this._structArray.uint16[this._pos2 + 10]; }\n set verticalTextBoxEndIndex(x: number) { this._structArray.uint16[this._pos2 + 10] = x; }\n get iconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 11]; }\n set iconBoxStartIndex(x: number) { this._structArray.uint16[this._pos2 + 11] = x; }\n get iconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 12]; }\n set iconBoxEndIndex(x: number) { this._structArray.uint16[this._pos2 + 12] = x; }\n get featureIndex() { return this._structArray.uint16[this._pos2 + 13]; }\n set featureIndex(x: number) { this._structArray.uint16[this._pos2 + 13] = x; }\n get numHorizontalGlyphVertices() { return this._structArray.uint16[this._pos2 + 14]; }\n set numHorizontalGlyphVertices(x: number) { this._structArray.uint16[this._pos2 + 14] = x; }\n get numVerticalGlyphVertices() { return this._structArray.uint16[this._pos2 + 15]; }\n set numVerticalGlyphVertices(x: number) { this._structArray.uint16[this._pos2 + 15] = x; }\n get numIconVertices() { return this._structArray.uint16[this._pos2 + 16]; }\n set numIconVertices(x: number) { this._structArray.uint16[this._pos2 + 16] = x; }\n get crossTileID() { return this._structArray.uint32[this._pos4 + 9]; }\n set crossTileID(x: number) { this._structArray.uint32[this._pos4 + 9] = x; }\n get textBoxScale() { return this._structArray.float32[this._pos4 + 10]; }\n set textBoxScale(x: number) { this._structArray.float32[this._pos4 + 10] = x; }\n get radialTextOffset() { return this._structArray.float32[this._pos4 + 11]; }\n set radialTextOffset(x: number) { this._structArray.float32[this._pos4 + 11] = x; }\n}\n\nSymbolInstanceStruct.prototype.size = 48;\n\nexport type SymbolInstance = SymbolInstanceStruct;\n\n/**\n * @private\n */\nexport class SymbolInstanceArray extends StructArrayLayout6i11ui1ul2f48 {\n /**\n * Return the SymbolInstanceStruct at the given location in the array.\n * @param {number} index The index of the element.\n */\n get(index: number): SymbolInstanceStruct {\n assert(!this.isTransferred);\n return new SymbolInstanceStruct(this, index);\n }\n}\n\nregister('SymbolInstanceArray', SymbolInstanceArray);\n\nclass GlyphOffsetStruct extends Struct {\n _structArray: GlyphOffsetArray;\n offsetX: number;\n get offsetX() { return this._structArray.float32[this._pos4 + 0]; }\n set offsetX(x: number) { this._structArray.float32[this._pos4 + 0] = x; }\n}\n\nGlyphOffsetStruct.prototype.size = 4;\n\nexport type GlyphOffset = GlyphOffsetStruct;\n\n/**\n * @private\n */\nexport class GlyphOffsetArray extends StructArrayLayout1f4 {\n getoffsetX(index: number) { return this.float32[index * 1 + 0]; }\n /**\n * Return the GlyphOffsetStruct at the given location in the array.\n * @param {number} index The index of the element.\n */\n get(index: number): GlyphOffsetStruct {\n assert(!this.isTransferred);\n return new GlyphOffsetStruct(this, index);\n }\n}\n\nregister('GlyphOffsetArray', GlyphOffsetArray);\n\nclass SymbolLineVertexStruct extends Struct {\n _structArray: SymbolLineVertexArray;\n x: number;\n y: number;\n tileUnitDistanceFromAnchor: number;\n get x() { return this._structArray.int16[this._pos2 + 0]; }\n set x(x: number) { this._structArray.int16[this._pos2 + 0] = x; }\n get y() { return this._structArray.int16[this._pos2 + 1]; }\n set y(x: number) { this._structArray.int16[this._pos2 + 1] = x; }\n get tileUnitDistanceFromAnchor() { return this._structArray.int16[this._pos2 + 2]; }\n set tileUnitDistanceFromAnchor(x: number) { this._structArray.int16[this._pos2 + 2] = x; }\n}\n\nSymbolLineVertexStruct.prototype.size = 6;\n\nexport type SymbolLineVertex = SymbolLineVertexStruct;\n\n/**\n * @private\n */\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 * Return the SymbolLineVertexStruct at the given location in the array.\n * @param {number} index The index of the element.\n */\n get(index: number): SymbolLineVertexStruct {\n assert(!this.isTransferred);\n return new SymbolLineVertexStruct(this, index);\n }\n}\n\nregister('SymbolLineVertexArray', SymbolLineVertexArray);\n\nclass FeatureIndexStruct extends Struct {\n _structArray: FeatureIndexArray;\n featureIndex: number;\n sourceLayerIndex: number;\n bucketIndex: number;\n get featureIndex() { return this._structArray.uint32[this._pos4 + 0]; }\n set featureIndex(x: number) { this._structArray.uint32[this._pos4 + 0] = x; }\n get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 2]; }\n set sourceLayerIndex(x: number) { this._structArray.uint16[this._pos2 + 2] = x; }\n get bucketIndex() { return this._structArray.uint16[this._pos2 + 3]; }\n set bucketIndex(x: number) { this._structArray.uint16[this._pos2 + 3] = x; }\n}\n\nFeatureIndexStruct.prototype.size = 8;\n\nexport type FeatureIndex = FeatureIndexStruct;\n\n/**\n * @private\n */\nexport class FeatureIndexArray extends StructArrayLayout1ul2ui8 {\n /**\n * Return the FeatureIndexStruct at the given location in the array.\n * @param {number} index The index of the element.\n */\n get(index: number): FeatureIndexStruct {\n assert(!this.isTransferred);\n return new FeatureIndexStruct(this, index);\n }\n}\n\nregister('FeatureIndexArray', FeatureIndexArray);\n\nexport {\n StructArrayLayout2i4,\n StructArrayLayout4i8,\n StructArrayLayout2i4i12,\n StructArrayLayout2i4ub8,\n StructArrayLayout8ui16,\n StructArrayLayout4i4ui16,\n StructArrayLayout3f12,\n StructArrayLayout1ul4,\n StructArrayLayout6i1ul2ui2i24,\n StructArrayLayout2i2i2i12,\n StructArrayLayout2ub2f12,\n StructArrayLayout2i2ui3ul3ui2f3ub1ul44,\n StructArrayLayout6i11ui1ul2f48,\n StructArrayLayout1f4,\n StructArrayLayout3i6,\n StructArrayLayout1ul2ui8,\n StructArrayLayout3ui6,\n StructArrayLayout2ui4,\n StructArrayLayout1ui2,\n StructArrayLayout2f8,\n StructArrayLayout4f16,\n StructArrayLayout2i4 as PosArray,\n StructArrayLayout4i8 as RasterBoundsArray,\n StructArrayLayout2i4 as CircleLayoutArray,\n StructArrayLayout2i4 as FillLayoutArray,\n StructArrayLayout2i4i12 as FillExtrusionLayoutArray,\n StructArrayLayout2i4 as HeatmapLayoutArray,\n StructArrayLayout2i4ub8 as LineLayoutArray,\n StructArrayLayout8ui16 as PatternLayoutArray,\n StructArrayLayout4i4ui16 as SymbolLayoutArray,\n StructArrayLayout3f12 as SymbolDynamicLayoutArray,\n StructArrayLayout1ul4 as SymbolOpacityArray,\n StructArrayLayout2i2i2i12 as CollisionBoxLayoutArray,\n StructArrayLayout2i2i2i12 as CollisionCircleLayoutArray,\n StructArrayLayout2ub2f12 as CollisionVertexArray,\n StructArrayLayout3ui6 as TriangleIndexArray,\n StructArrayLayout2ui4 as LineIndexArray,\n StructArrayLayout1ui2 as LineStripIndexArray\n};\n","// @flow\nimport { 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","// @flow\n\nimport { 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\nexport type Segment = {\n sortKey: number | void,\n vertexOffset: number,\n primitiveOffset: number,\n vertexLength: number,\n primitiveLength: number,\n vaos: {[string]: VertexArrayObject}\n}\n\nclass SegmentVector {\n static MAX_VERTEX_ARRAY_LENGTH: number;\n segments: Array;\n\n constructor(segments?: Array = []) {\n this.segments = segments;\n }\n\n prepareSegment(numVertices: number, layoutVertexArray: StructArray, indexArray: StructArray, sortKey?: number): 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 }: 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(vertexOffset: number, primitiveOffset: number, vertexLength: number, primitiveLength: number): 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 * @private\n * @readonly\n */\nSegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1;\n\nregister('SegmentVector', SegmentVector);\nexport default SegmentVector;\n","// @flow\n\nimport { 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 *\n * @private\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","// @flow\n\nimport { register } from '../util/web_worker_transfer';\nimport assert from 'assert';\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 default 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: number, index: number, start: number, end: number) {\n this.ids.push(id);\n this.positions.push(index, start, end);\n }\n\n getPositions(id: number): Array {\n assert(this.indexed);\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] >= id) {\n j = m;\n } else {\n i = m + 1;\n }\n }\n const positions = [];\n while (this.ids[i] === id) {\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 transferables.push(ids.buffer, positions.buffer);\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: any);\n map.positions = (obj.positions: any);\n map.indexed = true;\n return map;\n }\n}\n\n// custom quicksort that sorts ids, indices and offsets together (by ids)\nfunction sort(ids, positions, left, right) {\n if (left >= right) return;\n\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 sort(ids, positions, left, j);\n sort(ids, positions, j + 1, right);\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","// @flow\n\nimport Color from '../style-spec/util/color';\n\nimport type Context from '../gl/context';\n\nexport type UniformValues\n = $Exact<$ObjMap(u: Uniform) => V>>;\nexport type UniformLocations = {[string]: WebGLUniformLocation};\n\nclass Uniform {\n gl: WebGLRenderingContext;\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 +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<[number, number]> {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = [0, 0];\n }\n\n set(v: [number, number]): 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<[number, number, number]> {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = [0, 0, 0];\n }\n\n set(v: [number, number, number]): 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<[number, number, number, number]> {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = [0, 0, 0, 0];\n }\n\n set(v: [number, number, number, number]): 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);\nclass UniformMatrix4f extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = emptyMat4;\n }\n\n set(v: Float32Array): 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\nexport type UniformBindings = {[string]: Uniform};\n","// @flow\n\nimport { packUint8ToFloat } from '../shaders/encode_attribute';\nimport Color from '../style-spec/util/color';\nimport { supportsPropertyExpression } from '../style-spec/util/properties';\nimport { register, serialize, deserialize } from '../util/web_worker_transfer';\nimport { PossiblyEvaluatedPropertyValue } from '../style/properties';\nimport { StructArrayLayout1f4, StructArrayLayout2f8, StructArrayLayout4f16, PatternLayoutArray } from './array_types';\n\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport FeaturePositionMap from './feature_position_map';\nimport {\n Uniform,\n Uniform1f,\n UniformColor,\n Uniform4f,\n type UniformLocations\n} from '../render/uniform_binding';\n\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} from '../style-spec/expression';\nimport type {PossiblyEvaluated} from '../style/properties';\nimport type {FeatureStates} from '../source/source_state';\nimport type {FormattedSection} from '../style-spec/expression/types/formatted';\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 multliple 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 accomodate this.\n *\n * @private\n */\n\ninterface Binder {\n maxValue: number;\n uniformNames: Array;\n\n populatePaintArray(length: number, feature: Feature, imagePositions: {[string]: ImagePosition}, formattedSection?: FormattedSection): void;\n updatePaintArray(start: number, length: number, feature: Feature, featureState: FeatureState, imagePositions: {[string]: ImagePosition}): void;\n upload(Context): void;\n destroy(): void;\n\n defines(): Array;\n setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition): void;\n\n setUniforms(context: Context, uniform: Uniform<*>, globals: GlobalProperties,\n currentValue: PossiblyEvaluatedPropertyValue, uniformName: string): void;\n\n getBinding(context: Context, location: WebGLUniformLocation): $Shape>;\n}\n\nclass ConstantBinder implements Binder {\n value: T;\n names: Array;\n maxValue: number;\n type: string;\n uniformNames: Array;\n\n constructor(value: T, names: Array, type: string) {\n this.value = value;\n this.names = names;\n this.uniformNames = this.names.map(name => `u_${name}`);\n this.type = type;\n this.maxValue = -Infinity;\n }\n\n defines() {\n return this.names.map(name => `#define HAS_UNIFORM_u_${name}`);\n }\n setConstantPatternPositions() {}\n populatePaintArray() {}\n updatePaintArray() {}\n upload() {}\n destroy() {}\n\n setUniforms(context: Context, uniform: Uniform<*>, globals: GlobalProperties,\n currentValue: PossiblyEvaluatedPropertyValue): void {\n uniform.set(currentValue.constantOr(this.value));\n }\n\n getBinding(context: Context, location: WebGLUniformLocation): $Shape> {\n return (this.type === 'color') ?\n new UniformColor(context, location) :\n new Uniform1f(context, location);\n }\n\n static serialize(binder: ConstantBinder) {\n const {value, names, type} = binder;\n return {value: serialize(value), names, type};\n }\n\n static deserialize(serialized: {value: T, names: Array, type: string}) {\n const {value, names, type} = serialized;\n return new ConstantBinder(deserialize(value), names, type);\n }\n}\n\nclass CrossFadedConstantBinder implements Binder {\n value: T;\n names: Array;\n uniformNames: Array;\n patternPositions: {[string]: ?Array};\n type: string;\n maxValue: number;\n\n constructor(value: T, names: Array, type: string) {\n this.value = value;\n this.names = names;\n this.uniformNames = this.names.map(name => `u_${name}`);\n this.type = type;\n this.maxValue = -Infinity;\n this.patternPositions = {patternTo: null, patternFrom: null};\n }\n\n defines() {\n return this.names.map(name => `#define HAS_UNIFORM_u_${name}`);\n }\n\n populatePaintArray() {}\n updatePaintArray() {}\n upload() {}\n destroy() {}\n\n setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition) {\n this.patternPositions.patternTo = posTo.tlbr;\n this.patternPositions.patternFrom = posFrom.tlbr;\n }\n\n setUniforms(context: Context, uniform: Uniform<*>, globals: GlobalProperties,\n currentValue: PossiblyEvaluatedPropertyValue, uniformName: string) {\n const pos = this.patternPositions;\n if (uniformName === \"u_pattern_to\" && pos.patternTo) uniform.set(pos.patternTo);\n if (uniformName === \"u_pattern_from\" && pos.patternFrom) uniform.set(pos.patternFrom);\n }\n\n getBinding(context: Context, location: WebGLUniformLocation): $Shape> {\n return new Uniform4f(context, location);\n }\n}\n\nclass SourceExpressionBinder implements Binder {\n expression: SourceExpression;\n names: Array;\n uniformNames: Array;\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: Class) {\n this.expression = expression;\n this.names = names;\n this.type = type;\n this.uniformNames = this.names.map(name => `a_${name}`);\n this.maxValue = -Infinity;\n this.paintVertexAttributes = names.map((name) =>\n ({\n name: `a_${name}`,\n type: 'Float32',\n components: type === 'color' ? 2 : 1,\n offset: 0\n })\n );\n this.paintVertexArray = new PaintVertexArray();\n }\n\n defines() {\n return [];\n }\n\n setConstantPatternPositions() {}\n\n populatePaintArray(newLength: number, feature: Feature, imagePositions: {[string]: ImagePosition}, formattedSection?: FormattedSection) {\n const paintArray = this.paintVertexArray;\n\n const start = paintArray.length;\n paintArray.reserve(newLength);\n\n const value = this.expression.evaluate(new EvaluationParameters(0), feature, {}, formattedSection);\n\n if (this.type === 'color') {\n const color = packColor(value);\n for (let i = start; i < newLength; i++) {\n paintArray.emplaceBack(color[0], color[1]);\n }\n } else {\n for (let i = start; i < newLength; i++) {\n paintArray.emplaceBack(value);\n }\n\n this.maxValue = Math.max(this.maxValue, value);\n }\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState) {\n const paintArray = this.paintVertexArray;\n const value = this.expression.evaluate({zoom: 0}, feature, featureState);\n\n if (this.type === 'color') {\n const color = packColor(value);\n for (let i = start; i < end; i++) {\n paintArray.emplace(i, color[0], color[1]);\n }\n } else {\n for (let i = start; i < end; i++) {\n paintArray.emplace(i, value);\n }\n\n this.maxValue = Math.max(this.maxValue, 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 setUniforms(context: Context, uniform: Uniform<*>): void {\n uniform.set(0);\n }\n\n getBinding(context: Context, location: WebGLUniformLocation): Uniform1f {\n return new Uniform1f(context, location);\n }\n}\n\nclass CompositeExpressionBinder implements Binder {\n expression: CompositeExpression;\n names: Array;\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, layout: Class) {\n this.expression = expression;\n this.names = names;\n this.uniformNames = this.names.map(name => `u_${name}_t`);\n this.type = type;\n this.useIntegerZoom = useIntegerZoom;\n this.zoom = zoom;\n this.maxValue = -Infinity;\n const PaintVertexArray = layout;\n this.paintVertexAttributes = names.map((name) => {\n return {\n name: `a_${name}`,\n type: 'Float32',\n components: type === 'color' ? 4 : 2,\n offset: 0\n };\n });\n this.paintVertexArray = new PaintVertexArray();\n }\n\n defines() {\n return [];\n }\n\n setConstantPatternPositions() {}\n\n populatePaintArray(newLength: number, feature: Feature, imagePositions: {[string]: ImagePosition}, formattedSection?: FormattedSection) {\n const paintArray = this.paintVertexArray;\n\n const start = paintArray.length;\n paintArray.reserve(newLength);\n\n const min = this.expression.evaluate(new EvaluationParameters(this.zoom), feature, {}, formattedSection);\n const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1), feature, {}, formattedSection);\n\n if (this.type === 'color') {\n const minColor = packColor(min);\n const maxColor = packColor(max);\n for (let i = start; i < newLength; i++) {\n paintArray.emplaceBack(minColor[0], minColor[1], maxColor[0], maxColor[1]);\n }\n } else {\n for (let i = start; i < newLength; i++) {\n paintArray.emplaceBack(min, max);\n }\n this.maxValue = Math.max(this.maxValue, min, max);\n }\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState) {\n const paintArray = this.paintVertexArray;\n\n const min = this.expression.evaluate({zoom: this.zoom }, feature, featureState);\n const max = this.expression.evaluate({zoom: this.zoom + 1}, feature, featureState);\n\n if (this.type === 'color') {\n const minColor = packColor(min);\n const maxColor = packColor(max);\n for (let i = start; i < end; i++) {\n paintArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]);\n }\n } else {\n for (let i = start; i < end; i++) {\n paintArray.emplace(i, min, max);\n }\n this.maxValue = Math.max(this.maxValue, min, 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 interpolationFactor(currentZoom: number) {\n if (this.useIntegerZoom) {\n return this.expression.interpolationFactor(Math.floor(currentZoom), this.zoom, this.zoom + 1);\n } else {\n return this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1);\n }\n }\n\n setUniforms(context: Context, uniform: Uniform<*>,\n globals: GlobalProperties): void {\n uniform.set(this.interpolationFactor(globals.zoom));\n }\n\n getBinding(context: Context, location: WebGLUniformLocation): Uniform1f {\n return new Uniform1f(context, location);\n }\n}\n\nclass CrossFadedCompositeBinder implements Binder {\n expression: CompositeExpression;\n names: Array;\n uniformNames: Array;\n type: string;\n useIntegerZoom: boolean;\n zoom: number;\n maxValue: 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, names: Array, type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: Class, layerId: string) {\n\n this.expression = expression;\n this.names = names;\n this.type = type;\n this.uniformNames = this.names.map(name => `u_${name}_t`);\n this.useIntegerZoom = useIntegerZoom;\n this.zoom = zoom;\n this.maxValue = -Infinity;\n this.layerId = layerId;\n\n this.paintVertexAttributes = names.map((name) =>\n ({\n name: `a_${name}`,\n type: 'Uint16',\n components: 4,\n offset: 0\n })\n );\n\n this.zoomInPaintVertexArray = new PaintVertexArray();\n this.zoomOutPaintVertexArray = new PaintVertexArray();\n }\n\n defines() {\n return [];\n }\n\n setConstantPatternPositions() {}\n\n populatePaintArray(length: number, feature: Feature, imagePositions: {[string]: ImagePosition}) {\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\n const zoomInArray = this.zoomInPaintVertexArray;\n const zoomOutArray = this.zoomOutPaintVertexArray;\n const { layerId } = this;\n const start = zoomInArray.length;\n\n zoomInArray.reserve(length);\n zoomOutArray.reserve(length);\n\n if (imagePositions && feature.patterns && feature.patterns[layerId]) {\n const { min, mid, max } = feature.patterns[layerId];\n\n const imageMin = imagePositions[min];\n const imageMid = imagePositions[mid];\n const imageMax = imagePositions[max];\n\n if (!imageMin || !imageMid || !imageMax) return;\n\n for (let i = start; i < length; i++) {\n zoomInArray.emplaceBack(\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 );\n\n zoomOutArray.emplaceBack(\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 );\n }\n }\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState, imagePositions: {[string]: ImagePosition}) {\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\n const zoomInArray = this.zoomInPaintVertexArray;\n const zoomOutArray = this.zoomOutPaintVertexArray;\n const { layerId } = this;\n\n if (imagePositions && feature.patterns && feature.patterns[layerId]) {\n const {min, mid, max} = feature.patterns[layerId];\n const imageMin = imagePositions[min];\n const imageMid = imagePositions[mid];\n const imageMax = imagePositions[max];\n\n if (!imageMin || !imageMid || !imageMax) return;\n for (let i = start; i < end; i++) {\n zoomInArray.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 );\n\n zoomOutArray.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 );\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, this.paintVertexAttributes, this.expression.isStateDependent);\n this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, this.paintVertexAttributes, 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 setUniforms(context: Context, uniform: Uniform<*>): void {\n uniform.set(0);\n }\n\n getBinding(context: Context, location: WebGLUniformLocation): $Shape> {\n return new Uniform1f(context, location);\n }\n}\n\n/**\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 *\n * @private\n */\nexport default class ProgramConfiguration {\n binders: { [string]: Binder };\n cacheKey: string;\n layoutAttributes: Array;\n\n _buffers: Array;\n _featureMap: FeaturePositionMap;\n _bufferOffset: number;\n\n constructor() {\n this.binders = {};\n this.cacheKey = '';\n this._buffers = [];\n this._featureMap = new FeaturePositionMap();\n this._bufferOffset = 0;\n }\n\n static createDynamic(layer: Layer, zoom: number, filterProperties: (string) => boolean) {\n const self = new ProgramConfiguration();\n const keys = [];\n\n for (const property in layer.paint._values) {\n if (!filterProperties(property)) continue;\n const value = layer.paint.get(property);\n if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {\n continue;\n }\n const names = paintAttributeNames(property, layer.type);\n const type = value.property.specification.type;\n const useIntegerZoom = value.property.useIntegerZoom;\n const isCrossFaded = value.property.specification['property-type'] === 'cross-faded' ||\n value.property.specification['property-type'] === 'cross-faded-data-driven';\n\n if (isCrossFaded) {\n if (value.value.kind === 'constant') {\n self.binders[property] = new CrossFadedConstantBinder(value.value.value, names, type);\n keys.push(`/u_${property}`);\n } else {\n const StructArrayLayout = layoutType(property, type, 'source');\n self.binders[property] = new CrossFadedCompositeBinder(value.value, names, type, useIntegerZoom, zoom, StructArrayLayout, layer.id);\n keys.push(`/a_${property}`);\n }\n } else if (value.value.kind === 'constant') {\n self.binders[property] = new ConstantBinder(value.value.value, names, type);\n keys.push(`/u_${property}`);\n } else if (value.value.kind === 'source') {\n const StructArrayLayout = layoutType(property, type, 'source');\n self.binders[property] = new SourceExpressionBinder(value.value, names, type, StructArrayLayout);\n keys.push(`/a_${property}`);\n } else {\n const StructArrayLayout = layoutType(property, type, 'composite');\n self.binders[property] = new CompositeExpressionBinder(value.value, names, type, useIntegerZoom, zoom, StructArrayLayout);\n keys.push(`/z_${property}`);\n }\n }\n\n self.cacheKey = keys.sort().join('');\n\n return self;\n }\n\n populatePaintArrays(newLength: number, feature: Feature, index: number, imagePositions: {[string]: ImagePosition}, formattedSection?: FormattedSection) {\n for (const property in this.binders) {\n const binder = this.binders[property];\n binder.populatePaintArray(newLength, feature, imagePositions, formattedSection);\n }\n if (feature.id !== undefined) {\n this._featureMap.add(+feature.id, index, this._bufferOffset, newLength);\n }\n this._bufferOffset = newLength;\n }\n setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition) {\n for (const property in this.binders) {\n const binder = this.binders[property];\n binder.setConstantPatternPositions(posTo, posFrom);\n }\n }\n\n updatePaintArrays(featureStates: FeatureStates, vtLayer: VectorTileLayer, layer: TypedStyleLayer, imagePositions: {[string]: ImagePosition}): boolean {\n let dirty: boolean = false;\n for (const id in featureStates) {\n const positions = this._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 ConstantBinder || binder instanceof CrossFadedConstantBinder) continue;\n if ((binder: any).expression.isStateDependent === true) {\n //AHM: Remove after https://github.com/mapbox/mapbox-gl-js/issues/6255\n const value = layer.paint.get(property);\n (binder: any).expression = value.value;\n binder.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 result.push(...this.binders[property].defines());\n }\n return result;\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 for (const name of binder.uniformNames) {\n if (locations[name]) {\n const binding = binder.getBinding(context, locations[name]);\n uniforms.push({name, property, binding});\n }\n }\n }\n return uniforms;\n }\n\n setUniforms(context: Context, binderUniforms: Array, properties: PossiblyEvaluated, globals: GlobalProperties) {\n // Uniform state bindings are owned by the Program, but we set them\n // from within the ProgramConfiguraton's binder members.\n for (const {name, property, binding} of binderUniforms) {\n this.binders[property].setUniforms(context, binding, globals, properties.get(property), name);\n }\n }\n\n updatePatternPaintBuffers(crossfade: CrossfadeParameters) {\n const buffers = [];\n\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof CrossFadedCompositeBinder) {\n const patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer;\n if (patternVertexBuffer) buffers.push(patternVertexBuffer);\n } else if ((binder instanceof SourceExpressionBinder ||\n binder instanceof CompositeExpressionBinder) &&\n binder.paintVertexBuffer\n ) {\n buffers.push(binder.paintVertexBuffer);\n }\n }\n\n this._buffers = buffers;\n }\n\n upload(context: Context) {\n for (const property in this.binders) {\n this.binders[property].upload(context);\n }\n\n const buffers = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if ((binder instanceof SourceExpressionBinder ||\n binder instanceof CompositeExpressionBinder) &&\n binder.paintVertexBuffer\n ) {\n buffers.push(binder.paintVertexBuffer);\n }\n }\n this._buffers = buffers;\n }\n\n destroy() {\n for (const property in this.binders) {\n this.binders[property].destroy();\n }\n }\n}\n\nexport class ProgramConfigurationSet {\n programConfigurations: {[string]: ProgramConfiguration};\n needsUpload: boolean;\n\n constructor(layoutAttributes: Array, layers: $ReadOnlyArray, zoom: number, filterProperties: (string) => boolean = () => true) {\n this.programConfigurations = {};\n for (const layer of layers) {\n this.programConfigurations[layer.id] = ProgramConfiguration.createDynamic(layer, zoom, filterProperties);\n this.programConfigurations[layer.id].layoutAttributes = layoutAttributes;\n }\n this.needsUpload = false;\n }\n\n populatePaintArrays(length: number, feature: Feature, index: number, imagePositions: {[string]: ImagePosition}, formattedSection?: FormattedSection) {\n for (const key in this.programConfigurations) {\n this.programConfigurations[key].populatePaintArrays(length, feature, index, imagePositions, formattedSection);\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, 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'],\n 'fill-pattern': ['pattern_to', 'pattern_from'],\n 'fill-extrusion-pattern': ['pattern_to', 'pattern_from'],\n };\n\n return attributeNameExceptions[property] ||\n [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] ||\n 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","// @flow\n\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 *\n * @private\n * @readonly\n */\nexport default 8192;\n","// @flow\n\nimport { warnOnce, clamp } from '../util/util';\n\nimport EXTENT from './extent';\n\nimport type Point from '@mapbox/point-geometry';\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 cordinates within [-Infinity, Infinity]. Our range is limited by the\n// number of bits used to represent the coordinate.\nfunction createBounds(bits) {\n return {\n min: -1 * Math.pow(2, bits - 1),\n max: Math.pow(2, bits - 1) - 1\n };\n}\n\nconst bounds = createBounds(15);\n\n/**\n * Loads a geometry from a VectorTileFeature and scales it to the common extent\n * used internally.\n * @param {VectorTileFeature} feature\n * @private\n */\nexport default 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 point.x = Math.round(point.x * scale);\n point.y = Math.round(point.y * scale);\n\n if (point.x < bounds.min || point.x > bounds.max || point.y < bounds.min || point.y > bounds.max) {\n warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size');\n point.x = clamp(point.x, bounds.min, bounds.max);\n point.y = clamp(point.y, bounds.min, bounds.max);\n }\n }\n }\n return geometry;\n}\n","// @flow\n\nimport { CircleLayoutArray } from '../array_types';\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 EXTENT from '../extent';\nimport { register } from '../../util/web_worker_transfer';\nimport EvaluationParameters from '../../style/evaluation_parameters';\n\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';\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 * 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 * @private\n */\nclass 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(layoutAttributes, 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) {\n const styleLayer = this.layers[0];\n const bucketFeatures = [];\n let circleSortKey = null;\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: any): CircleStyleLayer).layout.get('circle-sort-key');\n }\n\n for (const {feature, index, sourceLayerIndex} of features) {\n if (this.layers[0]._featureFilter(new EvaluationParameters(this.zoom), feature)) {\n const geometry = loadGeometry(feature);\n const sortKey = circleSortKey ?\n circleSortKey.evaluate(feature, {}) :\n undefined;\n\n const bucketFeature: BucketFeature = {\n id: feature.id,\n properties: feature.properties,\n type: feature.type,\n sourceLayerIndex,\n index,\n geometry,\n patterns: {},\n sortKey\n };\n\n bucketFeatures.push(bucketFeature);\n }\n }\n\n if (circleSortKey) {\n bucketFeatures.sort((a, b) => {\n // a.sortKey is always a number when in use\n return ((a.sortKey: any): number) - ((b.sortKey: any): number);\n });\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);\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) {\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, {});\n }\n}\n\nregister('CircleBucket', CircleBucket, {omit: ['layers']});\n\nexport default CircleBucket;\n","// @flow\n\nimport { 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 http://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","// @flow\n\nimport 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(property: string, layer: StyleLayer, bucket: CircleBucket<*> | LineBucket): number {\n const value = ((layer.paint: any).get(property): PossiblyEvaluatedPropertyValue).value;\n if (value.kind === 'constant') {\n return value.value;\n } else {\n const binders = bucket.programConfigurations.get(layer.id).binders;\n return binders[property].maxValue;\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","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nexport type LayoutProps = {|\n \"circle-sort-key\": DataDrivenProperty,\n|};\n\nconst layout: Properties = new Properties({\n \"circle-sort-key\": new DataDrivenProperty(styleSpec[\"layout_circle\"][\"circle-sort-key\"]),\n});\n\nexport type PaintProps = {|\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\nconst paint: Properties = new Properties({\n \"circle-radius\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-radius\"]),\n \"circle-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-color\"]),\n \"circle-blur\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-blur\"]),\n \"circle-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-opacity\"]),\n \"circle-translate\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate\"]),\n \"circle-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate-anchor\"]),\n \"circle-pitch-scale\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-scale\"]),\n \"circle-pitch-alignment\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-alignment\"]),\n \"circle-stroke-width\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-width\"]),\n \"circle-stroke-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-color\"]),\n \"circle-stroke-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties, layout: Properties\n}>);\n","/**\r\n * Common utilities\r\n * @module glMatrix\r\n */\n// Configuration Constants\nexport var EPSILON = 0.000001;\nexport var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nexport var RANDOM = Math.random;\n/**\r\n * Sets the type of array used when creating new vectors and matrices\r\n *\r\n * @param {Type} type Array type, such as Float32Array or Array\r\n */\n\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\nvar degree = Math.PI / 180;\n/**\r\n * Convert Degree To Radian\r\n *\r\n * @param {Number} a Angle in Degrees\r\n */\n\nexport function toRadian(a) {\n return a * degree;\n}\n/**\r\n * Tests whether or not the arguments have approximately the same value, within an absolute\r\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\r\n * than or equal to 1.0, and a relative tolerance is used for larger values)\r\n *\r\n * @param {Number} a The first number to test.\r\n * @param {Number} b The second number to test.\r\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\r\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/**\r\n * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.\r\n * @module mat4\r\n */\n\n/**\r\n * Creates a new identity mat4\r\n *\r\n * @returns {mat4} a new 4x4 matrix\r\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/**\r\n * Creates a new mat4 initialized with values from an existing matrix\r\n *\r\n * @param {mat4} a matrix to clone\r\n * @returns {mat4} a new 4x4 matrix\r\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/**\r\n * Copy the values from one mat4 to another\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the source matrix\r\n * @returns {mat4} out\r\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/**\r\n * Create a new mat4 with the given values\r\n *\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\r\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\r\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\r\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\r\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\r\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\r\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\r\n * @returns {mat4} A new mat4\r\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/**\r\n * Set the components of a mat4 to the given values\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\r\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\r\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\r\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\r\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\r\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\r\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\r\n * @returns {mat4} out\r\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/**\r\n * Set a mat4 to the identity matrix\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @returns {mat4} out\r\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/**\r\n * Transpose the values of a mat4\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the source matrix\r\n * @returns {mat4} out\r\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/**\r\n * Inverts a mat4\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the source matrix\r\n * @returns {mat4} out\r\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/**\r\n * Calculates the adjugate of a mat4\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the source matrix\r\n * @returns {mat4} out\r\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/**\r\n * Calculates the determinant of a mat4\r\n *\r\n * @param {mat4} a the source matrix\r\n * @returns {Number} determinant of a\r\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/**\r\n * Multiplies two mat4s\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the first operand\r\n * @param {mat4} b the second operand\r\n * @returns {mat4} out\r\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/**\r\n * Translate a mat4 by the given vector\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to translate\r\n * @param {vec3} v vector to translate by\r\n * @returns {mat4} out\r\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/**\r\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to scale\r\n * @param {vec3} v the vec3 to scale the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Rotates a mat4 by the given angle around the given axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @param {vec3} axis the axis to rotate around\r\n * @returns {mat4} out\r\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/**\r\n * Rotates a matrix by the given angle around the X axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Rotates a matrix by the given angle around the Y axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Rotates a matrix by the given angle around the Z axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, dest, vec);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {vec3} v Translation vector\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a vector scaling\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.scale(dest, dest, vec);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {vec3} v Scaling vector\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a given angle around a given axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotate(dest, dest, rad, axis);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @param {vec3} axis the axis to rotate around\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from the given angle around the X axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotateX(dest, dest, rad);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from the given angle around the Y axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotateY(dest, dest, rad);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from the given angle around the Z axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotateZ(dest, dest, rad);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a quaternion rotation and vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, vec);\r\n * let quatMat = mat4.create();\r\n * quat4.toMat4(quat, quatMat);\r\n * mat4.multiply(dest, quatMat);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat4} q Rotation quaternion\r\n * @param {vec3} v Translation vector\r\n * @returns {mat4} out\r\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/**\r\n * Creates a new mat4 from a dual quat.\r\n *\r\n * @param {mat4} out Matrix\r\n * @param {quat2} a Dual Quaternion\r\n * @returns {mat4} mat4 receiving operation result\r\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/**\r\n * Returns the translation vector component of a transformation\r\n * matrix. If a matrix is built with fromRotationTranslation,\r\n * the returned vector will be the same as the translation vector\r\n * originally supplied.\r\n * @param {vec3} out Vector to receive translation component\r\n * @param {mat4} mat Matrix to be decomposed (input)\r\n * @return {vec3} out\r\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/**\r\n * Returns the scaling factor component of a transformation\r\n * matrix. If a matrix is built with fromRotationTranslationScale\r\n * with a normalized Quaternion paramter, the returned vector will be\r\n * the same as the scaling vector\r\n * originally supplied.\r\n * @param {vec3} out Vector to receive scaling factor component\r\n * @param {mat4} mat Matrix to be decomposed (input)\r\n * @return {vec3} out\r\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/**\r\n * Returns a quaternion representing the rotational component\r\n * of a transformation matrix. If a matrix is built with\r\n * fromRotationTranslation, the returned quaternion will be the\r\n * same as the quaternion originally supplied.\r\n * @param {quat} out Quaternion to receive the rotation component\r\n * @param {mat4} mat Matrix to be decomposed (input)\r\n * @return {quat} out\r\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/**\r\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, vec);\r\n * let quatMat = mat4.create();\r\n * quat4.toMat4(quat, quatMat);\r\n * mat4.multiply(dest, quatMat);\r\n * mat4.scale(dest, scale)\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat4} q Rotation quaternion\r\n * @param {vec3} v Translation vector\r\n * @param {vec3} s Scaling vector\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, vec);\r\n * mat4.translate(dest, origin);\r\n * let quatMat = mat4.create();\r\n * quat4.toMat4(quat, quatMat);\r\n * mat4.multiply(dest, quatMat);\r\n * mat4.scale(dest, scale)\r\n * mat4.translate(dest, negativeOrigin);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat4} q Rotation quaternion\r\n * @param {vec3} v Translation vector\r\n * @param {vec3} s Scaling vector\r\n * @param {vec3} o The origin vector around which to scale and rotate\r\n * @returns {mat4} out\r\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/**\r\n * Calculates a 4x4 matrix from the given quaternion\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat} q Quaternion to create matrix from\r\n *\r\n * @returns {mat4} out\r\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/**\r\n * Generates a frustum matrix with the given bounds\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {Number} left Left bound of the frustum\r\n * @param {Number} right Right bound of the frustum\r\n * @param {Number} bottom Bottom bound of the frustum\r\n * @param {Number} top Top bound of the frustum\r\n * @param {Number} near Near bound of the frustum\r\n * @param {Number} far Far bound of the frustum\r\n * @returns {mat4} out\r\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/**\r\n * Generates a perspective projection matrix with the given bounds.\r\n * Passing null/undefined/no value for far will generate infinite projection matrix.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {number} fovy Vertical field of view in radians\r\n * @param {number} aspect Aspect ratio. typically viewport width/height\r\n * @param {number} near Near bound of the frustum\r\n * @param {number} far Far bound of the frustum, can be null or Infinity\r\n * @returns {mat4} out\r\n */\n\nexport function perspective(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/**\r\n * Generates a perspective projection matrix with the given field of view.\r\n * This is primarily useful for generating projection matrices to be used\r\n * with the still experiemental WebVR API.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\r\n * @param {number} near Near bound of the frustum\r\n * @param {number} far Far bound of the frustum\r\n * @returns {mat4} out\r\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/**\r\n * Generates a orthogonal projection matrix with the given bounds\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {number} left Left bound of the frustum\r\n * @param {number} right Right bound of the frustum\r\n * @param {number} bottom Bottom bound of the frustum\r\n * @param {number} top Top bound of the frustum\r\n * @param {number} near Near bound of the frustum\r\n * @param {number} far Far bound of the frustum\r\n * @returns {mat4} out\r\n */\n\nexport function ortho(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/**\r\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\r\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {vec3} eye Position of the viewer\r\n * @param {vec3} center Point the viewer is looking at\r\n * @param {vec3} up vec3 pointing up\r\n * @returns {mat4} out\r\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/**\r\n * Generates a matrix that makes something look at something else.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {vec3} eye Position of the viewer\r\n * @param {vec3} center Point the viewer is looking at\r\n * @param {vec3} up vec3 pointing up\r\n * @returns {mat4} out\r\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/**\r\n * Returns a string representation of a mat4\r\n *\r\n * @param {mat4} a matrix to represent as a string\r\n * @returns {String} string representation of the matrix\r\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/**\r\n * Returns Frobenius norm of a mat4\r\n *\r\n * @param {mat4} a the matrix to calculate Frobenius norm of\r\n * @returns {Number} Frobenius norm\r\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], 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/**\r\n * Adds two mat4's\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the first operand\r\n * @param {mat4} b the second operand\r\n * @returns {mat4} out\r\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/**\r\n * Subtracts matrix b from matrix a\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the first operand\r\n * @param {mat4} b the second operand\r\n * @returns {mat4} out\r\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/**\r\n * Multiply each element of the matrix by a scalar.\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to scale\r\n * @param {Number} b amount to scale the matrix's elements by\r\n * @returns {mat4} out\r\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/**\r\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\r\n *\r\n * @param {mat4} out the receiving vector\r\n * @param {mat4} a the first operand\r\n * @param {mat4} b the second operand\r\n * @param {Number} scale the amount to scale b's elements by before adding\r\n * @returns {mat4} out\r\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/**\r\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {mat4} a The first matrix.\r\n * @param {mat4} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\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/**\r\n * Returns whether or not the matrices have approximately the same elements in the same position.\r\n *\r\n * @param {mat4} a The first matrix.\r\n * @param {mat4} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\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/**\r\n * Alias for {@link mat4.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link mat4.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\n/**\r\n * 3 Dimensional Vector\r\n * @module vec3\r\n */\n\n/**\r\n * Creates a new, empty vec3\r\n *\r\n * @returns {vec3} a new 3D vector\r\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/**\r\n * Creates a new vec3 initialized with values from an existing vector\r\n *\r\n * @param {vec3} a vector to clone\r\n * @returns {vec3} a new 3D vector\r\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/**\r\n * Calculates the length of a vec3\r\n *\r\n * @param {vec3} a vector to calculate length of\r\n * @returns {Number} length of a\r\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/**\r\n * Creates a new vec3 initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @returns {vec3} a new 3D vector\r\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/**\r\n * Copy the values from one vec3 to another\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the source vector\r\n * @returns {vec3} out\r\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/**\r\n * Set the components of a vec3 to the given values\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @returns {vec3} out\r\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/**\r\n * Adds two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} out\r\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/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} out\r\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/**\r\n * Multiplies two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} out\r\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/**\r\n * Divides two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} out\r\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/**\r\n * Math.ceil the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to ceil\r\n * @returns {vec3} out\r\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/**\r\n * Math.floor the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to floor\r\n * @returns {vec3} out\r\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/**\r\n * Returns the minimum of two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} out\r\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/**\r\n * Returns the maximum of two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} out\r\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/**\r\n * Math.round the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to round\r\n * @returns {vec3} out\r\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/**\r\n * Scales a vec3 by a scalar number\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec3} out\r\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/**\r\n * Adds two vec3's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec3} out\r\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/**\r\n * Calculates the euclidian distance between two vec3's\r\n *\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {Number} distance between a and b\r\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/**\r\n * Calculates the squared euclidian distance between two vec3's\r\n *\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {Number} squared distance between a and b\r\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/**\r\n * Calculates the squared length of a vec3\r\n *\r\n * @param {vec3} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\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/**\r\n * Negates the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to negate\r\n * @returns {vec3} out\r\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/**\r\n * Returns the inverse of the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to invert\r\n * @returns {vec3} out\r\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/**\r\n * Normalize a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to normalize\r\n * @returns {vec3} out\r\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/**\r\n * Calculates the dot product of two vec3's\r\n *\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {Number} dot product of a and b\r\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n/**\r\n * Computes the cross product of two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} out\r\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/**\r\n * Performs a linear interpolation between two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec3} out\r\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/**\r\n * Performs a hermite interpolation with two control points\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @param {vec3} c the third operand\r\n * @param {vec3} d the fourth operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec3} out\r\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/**\r\n * Performs a bezier interpolation with two control points\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @param {vec3} c the third operand\r\n * @param {vec3} d the fourth operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec3} out\r\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/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\r\n * @returns {vec3} out\r\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/**\r\n * Transforms the vec3 with a mat4.\r\n * 4th vector component is implicitly '1'\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the vector to transform\r\n * @param {mat4} m matrix to transform with\r\n * @returns {vec3} out\r\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/**\r\n * Transforms the vec3 with a mat3.\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the vector to transform\r\n * @param {mat3} m the 3x3 matrix to transform with\r\n * @returns {vec3} out\r\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/**\r\n * Transforms the vec3 with a quat\r\n * Can also be used for dual quaternions. (Multiply it with the real part)\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the vector to transform\r\n * @param {quat} q quaternion to transform with\r\n * @returns {vec3} out\r\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/**\r\n * Rotate a 3D vector around the x-axis\r\n * @param {vec3} out The receiving vec3\r\n * @param {vec3} a The vec3 point to rotate\r\n * @param {vec3} b The origin of the rotation\r\n * @param {Number} c The angle of rotation\r\n * @returns {vec3} out\r\n */\n\nexport function rotateX(out, a, b, c) {\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(c) - p[2] * Math.sin(c);\n r[2] = p[1] * Math.sin(c) + p[2] * Math.cos(c); //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/**\r\n * Rotate a 3D vector around the y-axis\r\n * @param {vec3} out The receiving vec3\r\n * @param {vec3} a The vec3 point to rotate\r\n * @param {vec3} b The origin of the rotation\r\n * @param {Number} c The angle of rotation\r\n * @returns {vec3} out\r\n */\n\nexport function rotateY(out, a, b, c) {\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(c) + p[0] * Math.cos(c);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(c) - p[0] * Math.sin(c); //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/**\r\n * Rotate a 3D vector around the z-axis\r\n * @param {vec3} out The receiving vec3\r\n * @param {vec3} a The vec3 point to rotate\r\n * @param {vec3} b The origin of the rotation\r\n * @param {Number} c The angle of rotation\r\n * @returns {vec3} out\r\n */\n\nexport function rotateZ(out, a, b, c) {\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(c) - p[1] * Math.sin(c);\n r[1] = p[0] * Math.sin(c) + p[1] * Math.cos(c);\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/**\r\n * Get the angle between two 3D vectors\r\n * @param {vec3} a The first operand\r\n * @param {vec3} b The second operand\r\n * @returns {Number} The angle in radians\r\n */\n\nexport function angle(a, b) {\n var tempA = fromValues(a[0], a[1], a[2]);\n var tempB = fromValues(b[0], b[1], b[2]);\n normalize(tempA, tempA);\n normalize(tempB, tempB);\n var cosine = dot(tempA, tempB);\n\n if (cosine > 1.0) {\n return 0;\n } else if (cosine < -1.0) {\n return Math.PI;\n } else {\n return Math.acos(cosine);\n }\n}\n/**\r\n * Set the components of a vec3 to zero\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @returns {vec3} out\r\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/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {vec3} a vector to represent as a string\r\n * @returns {String} string representation of the vector\r\n */\n\nexport function str(a) {\n return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')';\n}\n/**\r\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {vec3} a The first vector.\r\n * @param {vec3} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {vec3} a The first vector.\r\n * @param {vec3} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\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/**\r\n * Alias for {@link vec3.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec3.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec3.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec3.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec3.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec3.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec3.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec3s.\r\n *\r\n * @param {Array} a the array of vectors to iterate over\r\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\r\n * @param {Number} offset Number of elements to skip at the beginning of the array\r\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\r\n * @param {Function} fn Function to call for each vector in the array\r\n * @param {Object} [arg] additional argument to pass to fn\r\n * @returns {Array} a\r\n * @function\r\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/**\r\n * 4 Dimensional Vector\r\n * @module vec4\r\n */\n\n/**\r\n * Creates a new, empty vec4\r\n *\r\n * @returns {vec4} a new 4D vector\r\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/**\r\n * Creates a new vec4 initialized with values from an existing vector\r\n *\r\n * @param {vec4} a vector to clone\r\n * @returns {vec4} a new 4D vector\r\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/**\r\n * Creates a new vec4 initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {vec4} a new 4D vector\r\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/**\r\n * Copy the values from one vec4 to another\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the source vector\r\n * @returns {vec4} out\r\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/**\r\n * Set the components of a vec4 to the given values\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {vec4} out\r\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/**\r\n * Adds two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Multiplies two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Divides two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Math.ceil the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to ceil\r\n * @returns {vec4} out\r\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/**\r\n * Math.floor the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to floor\r\n * @returns {vec4} out\r\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/**\r\n * Returns the minimum of two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Returns the maximum of two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Math.round the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to round\r\n * @returns {vec4} out\r\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/**\r\n * Scales a vec4 by a scalar number\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec4} out\r\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/**\r\n * Adds two vec4's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec4} out\r\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/**\r\n * Calculates the euclidian distance between two vec4's\r\n *\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {Number} distance between a and b\r\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/**\r\n * Calculates the squared euclidian distance between two vec4's\r\n *\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {Number} squared distance between a and b\r\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/**\r\n * Calculates the length of a vec4\r\n *\r\n * @param {vec4} a vector to calculate length of\r\n * @returns {Number} length of a\r\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/**\r\n * Calculates the squared length of a vec4\r\n *\r\n * @param {vec4} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\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/**\r\n * Negates the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to negate\r\n * @returns {vec4} out\r\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/**\r\n * Returns the inverse of the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to invert\r\n * @returns {vec4} out\r\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/**\r\n * Normalize a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to normalize\r\n * @returns {vec4} out\r\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/**\r\n * Calculates the dot product of two vec4's\r\n *\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {Number} dot product of a and b\r\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/**\r\n * Returns the cross-product of three vectors in a 4-dimensional space\r\n *\r\n * @param {vec4} result the receiving vector\r\n * @param {vec4} U the first vector\r\n * @param {vec4} V the second vector\r\n * @param {vec4} W the third vector\r\n * @returns {vec4} result\r\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/**\r\n * Performs a linear interpolation between two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec4} out\r\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/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\r\n * @returns {vec4} out\r\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/**\r\n * Transforms the vec4 with a mat4.\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the vector to transform\r\n * @param {mat4} m matrix to transform with\r\n * @returns {vec4} out\r\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/**\r\n * Transforms the vec4 with a quat\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the vector to transform\r\n * @param {quat} q quaternion to transform with\r\n * @returns {vec4} out\r\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/**\r\n * Set the components of a vec4 to zero\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @returns {vec4} out\r\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/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {vec4} a vector to represent as a string\r\n * @returns {String} string representation of the vector\r\n */\n\nexport function str(a) {\n return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';\n}\n/**\r\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {vec4} a The first vector.\r\n * @param {vec4} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\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/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {vec4} a The first vector.\r\n * @param {vec4} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\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/**\r\n * Alias for {@link vec4.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec4.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec4.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec4.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec4.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec4.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec4.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec4s.\r\n *\r\n * @param {Array} a the array of vectors to iterate over\r\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\r\n * @param {Number} offset Number of elements to skip at the beginning of the array\r\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\r\n * @param {Function} fn Function to call for each vector in the array\r\n * @param {Object} [arg] additional argument to pass to fn\r\n * @returns {Array} a\r\n * @function\r\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}();","// @flow\n\nimport 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 from './circle_style_layer_properties';\nimport { Transitionable, Transitioning, Layout, PossiblyEvaluated } from '../properties';\nimport { vec4 } from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\n\nimport type { FeatureState } from '../../style-spec/expression';\nimport type Transform from '../../geo/transform';\nimport type {Bucket, BucketParameters} from '../../data/bucket';\nimport type {LayoutProps, PaintProps} from './circle_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass 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: 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(queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number,\n pixelPosMatrix: Float32Array): 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([], [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: Float32Array) {\n const point = vec4.transformMat4([], [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: Float32Array) {\n return queryGeometry.map((p) => {\n return projectPoint(p, pixelPosMatrix);\n });\n}\n\nexport default CircleStyleLayer;\n","// @flow\n\nimport CircleBucket from './circle_bucket';\n\nimport { register } from '../../util/web_worker_transfer';\n\nimport type HeatmapStyleLayer from '../../style/style_layer/heatmap_style_layer';\n\nclass 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\nexport default HeatmapBucket;\n","// @flow\n\nimport assert from 'assert';\n\nimport { register } from './web_worker_transfer';\n\nexport type Size = {\n width: number,\n height: number\n};\n\ntype Point = {\n x: number,\n y: number\n};\n\nfunction createImage(image: *, {width, height}: 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');\n }\n image.width = width;\n image.height = height;\n image.data = data;\n return image;\n}\n\nfunction resizeImage(image: *, {width, height}: 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: *, dstImg: *, srcPt: Point, dstPt: Point, 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 assert(srcData !== dstData);\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\n return dstImg;\n}\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: Point, dstPt: Point, size: Size) {\n copyImage(srcImg, dstImg, srcPt, dstPt, size, 1);\n }\n}\n\n// Not premultiplied, because ImageData is not premultiplied.\n// UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture.\nexport class RGBAImage {\n width: number;\n height: number;\n\n // data must be a Uint8Array instead of Uint8ClampedArray because texImage2D does not\n // support Uint8ClampedArray in all browsers\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: Point, dstPt: Point, size: Size) {\n copyImage(srcImg, dstImg, srcPt, dstPt, size, 4);\n }\n}\n\nregister('AlphaImage', AlphaImage);\nregister('RGBAImage', RGBAImage);\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\n\nexport type PaintProps = {|\n \"heatmap-radius\": DataDrivenProperty,\n \"heatmap-weight\": DataDrivenProperty,\n \"heatmap-intensity\": DataConstantProperty,\n \"heatmap-color\": ColorRampProperty,\n \"heatmap-opacity\": DataConstantProperty,\n|};\n\nconst paint: Properties = new Properties({\n \"heatmap-radius\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-radius\"]),\n \"heatmap-weight\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-weight\"]),\n \"heatmap-intensity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-intensity\"]),\n \"heatmap-color\": new ColorRampProperty(styleSpec[\"paint_heatmap\"][\"heatmap-color\"]),\n \"heatmap-opacity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties\n}>);\n","// @flow\n\nimport { RGBAImage } from './image';\n\nimport type {StylePropertyExpression} from '../style-spec/expression/index';\n\n/**\n * Given an expression that should evaluate to a color ramp, return\n * a 256x1 px RGBA image representing that ramp expression.\n *\n * @private\n */\nexport default function renderColorRamp(expression: StylePropertyExpression, colorRampEvaluationParameter: string): RGBAImage {\n const colorRampData = new Uint8Array(256 * 4);\n const evaluationGlobals = {};\n for (let i = 0, j = 0; i < 256; i++, j += 4) {\n evaluationGlobals[colorRampEvaluationParameter] = i / 255;\n const pxColor = expression.evaluate((evaluationGlobals: any));\n // the colors are being unpremultiplied because Color uses\n // premultiplied values, and the Texture class expects unpremultiplied ones\n colorRampData[j + 0] = Math.floor(pxColor.r * 255 / pxColor.a);\n colorRampData[j + 1] = Math.floor(pxColor.g * 255 / pxColor.a);\n colorRampData[j + 2] = Math.floor(pxColor.b * 255 / pxColor.a);\n colorRampData[j + 3] = Math.floor(pxColor.a * 255);\n }\n\n return new RGBAImage({width: 256, height: 1}, colorRampData);\n}\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport HeatmapBucket from '../../data/bucket/heatmap_bucket';\nimport { RGBAImage } from '../../util/image';\nimport properties from './heatmap_style_layer_properties';\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 {PaintProps} from './heatmap_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass HeatmapStyleLayer extends StyleLayer {\n\n heatmapFbo: ?Framebuffer;\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 // 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(expression, 'heatmapDensity');\n this.colorRampTexture = null;\n }\n\n resize() {\n if (this.heatmapFbo) {\n this.heatmapFbo.destroy();\n this.heatmapFbo = null;\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\nexport default HeatmapStyleLayer;\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\n\nexport type PaintProps = {|\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\nconst paint: Properties = new Properties({\n \"hillshade-illumination-direction\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-direction\"]),\n \"hillshade-illumination-anchor\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-anchor\"]),\n \"hillshade-exaggeration\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-exaggeration\"]),\n \"hillshade-shadow-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-shadow-color\"]),\n \"hillshade-highlight-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-highlight-color\"]),\n \"hillshade-accent-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-accent-color\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport properties from './hillshade_style_layer_properties';\nimport { Transitionable, Transitioning, PossiblyEvaluated } from '../properties';\n\nimport type {PaintProps} from './hillshade_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass 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\nexport default HillshadeStyleLayer;\n","// @flow\nimport { 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","'use strict';\n\nmodule.exports = earcut;\nmodule.exports.default = earcut;\n\nfunction earcut(data, holeIndices, dim) {\n\n dim = dim || 2;\n\n var hasHoles = holeIndices && holeIndices.length,\n outerLen = hasHoles ? holeIndices[0] * dim : data.length,\n outerNode = linkedList(data, 0, outerLen, dim, true),\n triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n var minX, minY, maxX, maxY, x, y, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = maxX = data[0];\n minY = maxY = data[1];\n\n for (var i = dim; i < outerLen; i += dim) {\n x = data[i];\n y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 1 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n var i, last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);\n } else {\n for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n var p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n var stop = ear,\n prev, next;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n prev = ear.prev;\n next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n // cut off the triangle\n triangles.push(prev.i / dim);\n triangles.push(ear.i / dim);\n triangles.push(next.i / dim);\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles, dim);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n var a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n var p = ear.next.next;\n\n while (p !== ear.prev) {\n if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n var a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // triangle bbox; min & max are calculated like this for speed\n var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),\n minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),\n maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),\n maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);\n\n // z-order range for the current triangle bbox;\n var minZ = zOrder(minTX, minTY, minX, minY, invSize),\n maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);\n\n var p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p !== ear.prev && p !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n !== ear.prev && n !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&\n 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 !== ear.prev && p !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&\n 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 !== ear.prev && n !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&\n area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles, dim) {\n var p = start;\n do {\n var a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i / dim);\n triangles.push(p.i / dim);\n triangles.push(b.i / dim);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n var a = start;\n do {\n var b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n var c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize);\n earcutLinked(c, triangles, dim, minX, minY, invSize);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n var queue = [],\n i, len, start, end, list;\n\n for (i = 0, len = holeIndices.length; i < len; i++) {\n start = holeIndices[i] * dim;\n end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareX);\n\n // process holes from left to right\n for (i = 0; i < queue.length; i++) {\n eliminateHole(queue[i], outerNode);\n outerNode = filterPoints(outerNode, outerNode.next);\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 outerNode = findHoleBridge(hole, outerNode);\n if (outerNode) {\n var b = splitPolygon(outerNode, hole);\n filterPoints(b, b.next);\n }\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n var p = outerNode,\n hx = hole.x,\n hy = hole.y,\n qx = -Infinity,\n m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n do {\n if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n if (x === hx) {\n if (hy === p.y) return p;\n if (hy === p.next.y) return p.next;\n }\n m = p.x < p.next.x ? p : p.next;\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n var stop = m,\n mx = m.x,\n my = m.y,\n tanMin = Infinity,\n tan;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n var p = start;\n do {\n if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n var i, p, q, e, tail, numMerges, pSize, qSize,\n inSize = 1;\n\n do {\n p = list;\n list = null;\n tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n q = p;\n pSize = 0;\n for (i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = 32767 * (x - minX) * invSize;\n y = 32767 * (y - minY) * invSize;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n var p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&\n (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&\n (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n var o1 = sign(area(p1, q1, p2));\n var o2 = sign(area(p1, q1, q2));\n var o3 = sign(area(p2, q2, p1));\n var o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n var p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n var p = a,\n inside = false,\n px = (a.x + b.x) / 2,\n py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n var a2 = new Node(a.i, a.x, a.y),\n b2 = new Node(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n var p = new Node(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction Node(i, x, y) {\n // vertex index in coordinates array\n this.i = i;\n\n // vertex coordinates\n this.x = x;\n this.y = y;\n\n // previous and next vertex nodes in a polygon ring\n this.prev = null;\n this.next = null;\n\n // z-order curve value\n this.z = null;\n\n // previous and next nodes in z-order\n this.prevZ = null;\n this.nextZ = null;\n\n // indicates whether this is a steiner point\n this.steiner = false;\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nearcut.deviation = function (data, holeIndices, dim, triangles) {\n var hasHoles = holeIndices && holeIndices.length;\n var outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (var i = 0, len = holeIndices.length; i < len; i++) {\n var start = holeIndices[i] * dim;\n var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n var trianglesArea = 0;\n for (i = 0; i < triangles.length; i += 3) {\n var a = triangles[i] * dim;\n var b = triangles[i + 1] * dim;\n var c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n};\n\nfunction signedArea(data, start, end, dim) {\n var sum = 0;\n for (var i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nearcut.flatten = function (data) {\n var dim = data[0][0].length,\n result = {vertices: [], holes: [], dimensions: dim},\n holeIndex = 0;\n\n for (var i = 0; i < data.length; i++) {\n for (var j = 0; j < data[i].length; j++) {\n for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);\n }\n if (i > 0) {\n holeIndex += data[i - 1].length;\n result.holes.push(holeIndex);\n }\n }\n return result;\n};\n","\nexport default function quickselect(arr, k, left, right, compare) {\n quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);\n}\n\nfunction quickselectStep(arr, k, left, right, compare) {\n\n while (right > left) {\n if (right - left > 600) {\n var n = right - left + 1;\n var m = k - left + 1;\n var z = Math.log(n);\n var s = 0.5 * Math.exp(2 * z / 3);\n var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n quickselectStep(arr, k, newLeft, newRight, compare);\n }\n\n var t = arr[k];\n var i = left;\n var j = right;\n\n swap(arr, left, k);\n if (compare(arr[right], t) > 0) swap(arr, left, right);\n\n while (i < j) {\n swap(arr, i, j);\n i++;\n j--;\n while (compare(arr[i], t) < 0) i++;\n while (compare(arr[j], t) > 0) j--;\n }\n\n if (compare(arr[left], t) === 0) swap(arr, left, j);\n else {\n j++;\n swap(arr, j, right);\n }\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\nfunction swap(arr, i, j) {\n var tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\nfunction defaultCompare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","// @flow\n\nimport quickselect from 'quickselect';\n\nimport { calculateSignedArea } from './util';\n\nimport type Point from '@mapbox/point-geometry';\n\n// classifies an array of rings into polygons with outer rings and holes\nexport default function classifyRings(rings: Array>, maxRings: number) {\n const len = rings.length;\n\n if (len <= 1) return [rings];\n\n const polygons = [];\n let polygon,\n ccw;\n\n for (let i = 0; i < len; i++) {\n const area = calculateSignedArea(rings[i]);\n if (area === 0) continue;\n\n (rings[i]: any).area = Math.abs(area);\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: any).push(rings[i]);\n }\n }\n if (polygon) polygons.push(polygon);\n\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) continue;\n quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas);\n polygons[j] = polygons[j].slice(0, maxRings);\n }\n }\n\n return polygons;\n}\n\nfunction compareAreas(a, b) {\n return b.area - a.area;\n}\n","// @flow\nimport 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';\n\ntype PatternStyleLayers =\n Array |\n Array |\n 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.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.get(`${type}-pattern`);\n\n const patternPropertyValue = patternProperty.value;\n if (patternPropertyValue.kind !== \"constant\") {\n const min = patternPropertyValue.evaluate({zoom: zoom - 1}, patternFeature, {});\n const mid = patternPropertyValue.evaluate({zoom}, patternFeature, {});\n const max = patternPropertyValue.evaluate({zoom: zoom + 1}, patternFeature, {});\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","// @flow\n\nimport { FillLayoutArray } from '../array_types';\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 '../../util/classify_rings';\nimport assert from 'assert';\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 EvaluationParameters from '../../style/evaluation_parameters';\n\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';\n\nclass 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(layoutAttributes, 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) {\n this.hasPattern = hasPattern('fill', this.layers, options);\n const fillSortKey = this.layers[0].layout.get('fill-sort-key');\n const bucketFeatures = [];\n\n for (const {feature, index, sourceLayerIndex} of features) {\n if (!this.layers[0]._featureFilter(new EvaluationParameters(this.zoom), feature)) continue;\n\n const geometry = loadGeometry(feature);\n const sortKey = fillSortKey ?\n fillSortKey.evaluate(feature, {}) :\n undefined;\n\n const bucketFeature: BucketFeature = {\n id: feature.id,\n properties: feature.properties,\n type: feature.type,\n sourceLayerIndex,\n index,\n geometry,\n patterns: {},\n sortKey\n };\n\n bucketFeatures.push(bucketFeature);\n }\n\n if (fillSortKey) {\n bucketFeatures.sort((a, b) => {\n // a.sortKey is always a number when in use\n return ((a.sortKey: any): number) - ((b.sortKey: any): number);\n });\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, {});\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, imagePositions: {[string]: ImagePosition}) {\n for (const feature of this.patternFeatures) {\n this.addFeature(feature, feature.geometry, feature.index, 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, imagePositions: {[string]: ImagePosition}) {\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 assert(indices.length % 3 === 0);\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);\n }\n}\n\nregister('FillBucket', FillBucket, {omit: ['layers', 'patternFeatures']});\n\nexport default FillBucket;\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nexport type LayoutProps = {|\n \"fill-sort-key\": DataDrivenProperty,\n|};\n\nconst layout: Properties = new Properties({\n \"fill-sort-key\": new DataDrivenProperty(styleSpec[\"layout_fill\"][\"fill-sort-key\"]),\n});\n\nexport type PaintProps = {|\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\nconst paint: Properties = new Properties({\n \"fill-antialias\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-antialias\"]),\n \"fill-opacity\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-opacity\"]),\n \"fill-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-color\"]),\n \"fill-outline-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-outline-color\"]),\n \"fill-translate\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate\"]),\n \"fill-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate-anchor\"]),\n \"fill-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-pattern\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties, layout: Properties\n}>);\n","// @flow\n\nimport 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 from './fill_style_layer_properties';\nimport { Transitionable, Transitioning, Layout, PossiblyEvaluated } from '../properties';\n\nimport type { FeatureState } from '../../style-spec/expression';\nimport type {BucketParameters} from '../../data/bucket';\nimport type Point from '@mapbox/point-geometry';\nimport type {LayoutProps, PaintProps} from './fill_style_layer_properties';\nimport type EvaluationParameters from '../evaluation_parameters';\nimport type Transform from '../../geo/transform';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass 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) {\n super.recalculate(parameters);\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(queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number): 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\nexport default FillStyleLayer;\n","// @flow\nimport { 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 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","// @flow\n\nimport { FillExtrusionLayoutArray } from '../array_types';\n\nimport { members as layoutAttributes } 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 '../../util/classify_rings';\nimport assert from 'assert';\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 EvaluationParameters from '../../style/evaluation_parameters';\n\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';\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\nclass 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 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.indexArray = new TriangleIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, 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\n populate(features: Array, options: PopulateParameters) {\n this.features = [];\n this.hasPattern = hasPattern('fill-extrusion', this.layers, options);\n\n for (const {feature, index, sourceLayerIndex} of features) {\n if (!this.layers[0]._featureFilter(new EvaluationParameters(this.zoom), feature)) continue;\n\n const geometry = loadGeometry(feature);\n\n const patternFeature: BucketFeature = {\n sourceLayerIndex,\n index,\n geometry,\n properties: feature.properties,\n type: feature.type,\n patterns: {}\n };\n\n if (typeof feature.id !== 'undefined') {\n patternFeature.id = feature.id;\n }\n\n if (this.hasPattern) {\n this.features.push(addPatternDependencies('fill-extrusion', this.layers, patternFeature, this.zoom, options));\n } else {\n this.addFeature(patternFeature, geometry, index, {});\n }\n\n options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index, true);\n }\n }\n\n addFeatures(options: PopulateParameters, imagePositions: {[string]: ImagePosition}) {\n for (const feature of this.features) {\n const {geometry} = feature;\n this.addFeature(feature, geometry, feature.index, 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;\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, imagePositions: {[string]: ImagePosition}) {\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 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\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\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 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\n flattened.push(p.x);\n flattened.push(p.y);\n }\n }\n\n const indices = earcut(flattened, holeIndices);\n assert(indices.length % 3 === 0);\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\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions);\n }\n}\n\nregister('FillExtrusionBucket', FillExtrusionBucket, {omit: ['layers', 'features']});\n\nexport default FillExtrusionBucket;\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.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\n\nexport type PaintProps = {|\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\nconst paint: Properties = new Properties({\n \"fill-extrusion-opacity\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-opacity\"]),\n \"fill-extrusion-color\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-color\"]),\n \"fill-extrusion-translate\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate\"]),\n \"fill-extrusion-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate-anchor\"]),\n \"fill-extrusion-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-pattern\"]),\n \"fill-extrusion-height\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-height\"]),\n \"fill-extrusion-base\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-base\"]),\n \"fill-extrusion-vertical-gradient\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-vertical-gradient\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties\n}>);\n","// @flow\n\nimport 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 from './fill_extrusion_style_layer_properties';\nimport { Transitionable, Transitioning, PossiblyEvaluated } from '../properties';\nimport {vec4} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\n\nimport type { FeatureState } from '../../style-spec/expression';\nimport type {BucketParameters} from '../../data/bucket';\nimport type {PaintProps} from './fill_extrusion_style_layer_properties';\nimport type Transform from '../../geo/transform';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass 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(queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number,\n pixelPosMatrix: Float32Array): 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\nfunction 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 const a = projectedFace[0];\n const b = projectedFace[1];\n const c = projectedFace[3];\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 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 return a.z * u + b.z * v + c.z * w;\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: Float32Array) {\n const projectedBase = [];\n const projectedTop = [];\n\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 = [];\n const ringTop = [];\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);\n b.z = baseZ / baseW;\n ringBase.push(b);\n\n const t = new Point(topX / topW, topY / topW);\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: Float32Array, transform: Transform, z: number) {\n const projectedQueryGeometry = [];\n for (const p of queryGeometry) {\n const v = [p.x, p.y, z, 1];\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\nexport default FillExtrusionStyleLayer;\n","// @flow\nimport { createLayout } from '../../util/struct_array';\n\nconst lineLayoutAttributes = createLayout([\n {name: 'a_pos_normal', components: 2, type: 'Int16'},\n {name: 'a_data', components: 4, type: 'Uint8'}\n], 4);\n\nexport default lineLayoutAttributes;\nexport const {members, size, alignment} = lineLayoutAttributes;\n","// @flow\n\nimport { LineLayoutArray } from '../array_types';\n\nimport { members as layoutAttributes } from './line_attributes';\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 EvaluationParameters from '../../style/evaluation_parameters';\n\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 type Context from '../../gl/context';\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';\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\n/**\n * @private\n */\nclass LineBucket implements Bucket {\n distance: number;\n totalDistance: number;\n scaledDistance: number;\n clipStart: number;\n clipEnd: number;\n\n e1: number;\n e2: number;\n\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: LineLayoutArray;\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 this.patternFeatures = [];\n\n this.layoutVertexArray = new LineLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, options.layers, options.zoom);\n this.segments = new SegmentVector();\n\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array, options: PopulateParameters) {\n this.hasPattern = hasPattern('line', this.layers, options);\n const lineSortKey = this.layers[0].layout.get('line-sort-key');\n const bucketFeatures = [];\n\n for (const {feature, index, sourceLayerIndex} of features) {\n if (!this.layers[0]._featureFilter(new EvaluationParameters(this.zoom), feature)) continue;\n\n const geometry = loadGeometry(feature);\n const sortKey = lineSortKey ?\n lineSortKey.evaluate(feature, {}) :\n undefined;\n\n const bucketFeature: BucketFeature = {\n id: feature.id,\n properties: feature.properties,\n type: feature.type,\n sourceLayerIndex,\n index,\n geometry,\n patterns: {},\n sortKey\n };\n\n bucketFeatures.push(bucketFeature);\n }\n\n if (lineSortKey) {\n bucketFeatures.sort((a, b) => {\n // a.sortKey is always a number when in use\n return ((a.sortKey: any): number) - ((b.sortKey: any): number);\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, {});\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, imagePositions: {[string]: ImagePosition}) {\n for (const feature of this.patternFeatures) {\n this.addFeature(feature, feature.geometry, feature.index, 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 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, 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\n for (const line of geometry) {\n this.addLine(line, feature, join, cap, miterLimit, roundLimit, index, imagePositions);\n }\n }\n\n addLine(vertices: Array, feature: BucketFeature, join: string, cap: string, miterLimit: number, roundLimit: number, index: number, imagePositions: {[string]: ImagePosition}) {\n this.distance = 0;\n this.scaledDistance = 0;\n this.totalDistance = 0;\n\n if (!!feature.properties &&\n feature.properties.hasOwnProperty('mapbox_clip_start') &&\n feature.properties.hasOwnProperty('mapbox_clip_end')) {\n\n this.clipStart = +feature.properties['mapbox_clip_start'];\n this.clipEnd = +feature.properties['mapbox_clip_end'];\n\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 }\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 = SHARP_CORNER_OFFSET * (EXTENT / (512 * this.overscaling));\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;\n let prevVertex = ((undefined: any): Point);\n let nextVertex = ((undefined: any): Point);\n let prevNormal = ((undefined: any): Point);\n let nextNormal = ((undefined: any): 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 = isPolygon && i === len - 1 ?\n vertices[first + 1] : // if the line is closed, we 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 this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions);\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 * @private\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.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 // scale down so that we can store longer distances while sacrificing precision.\n const linesofar = this.scaledDistance * 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 `linesofar` (shifted by 2 bites to make\n // room for the direction value). The upper 8 bits of `linesofar` are placed in\n // the `w` component.\n ((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | ((linesofar & 0x3F) << 2),\n linesofar >> 6);\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 updateDistance(prev: Point, next: Point) {\n this.distance += prev.dist(next);\n\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.totalDistance > 0 ?\n (this.clipStart + (this.clipEnd - this.clipStart) * this.distance / this.totalDistance) * (MAX_LINE_DISTANCE - 1) :\n this.distance;\n }\n}\n\nregister('LineBucket', LineBucket, {omit: ['layers', 'patternFeatures']});\n\nexport default LineBucket;\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nexport type LayoutProps = {|\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\nconst layout: Properties = new Properties({\n \"line-cap\": new DataConstantProperty(styleSpec[\"layout_line\"][\"line-cap\"]),\n \"line-join\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-join\"]),\n \"line-miter-limit\": new DataConstantProperty(styleSpec[\"layout_line\"][\"line-miter-limit\"]),\n \"line-round-limit\": new DataConstantProperty(styleSpec[\"layout_line\"][\"line-round-limit\"]),\n \"line-sort-key\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-sort-key\"]),\n});\n\nexport type PaintProps = {|\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\nconst paint: Properties = new Properties({\n \"line-opacity\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-opacity\"]),\n \"line-color\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-color\"]),\n \"line-translate\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate\"]),\n \"line-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate-anchor\"]),\n \"line-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-width\"]),\n \"line-gap-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-gap-width\"]),\n \"line-offset\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-offset\"]),\n \"line-blur\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-blur\"]),\n \"line-dasharray\": new CrossFadedProperty(styleSpec[\"paint_line\"][\"line-dasharray\"]),\n \"line-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_line\"][\"line-pattern\"]),\n \"line-gradient\": new ColorRampProperty(styleSpec[\"paint_line\"][\"line-gradient\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties, layout: Properties\n}>);\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport StyleLayer from '../style_layer';\nimport LineBucket from '../../data/bucket/line_bucket';\nimport { RGBAImage } from '../../util/image';\nimport { polygonIntersectsBufferedMultiLine } from '../../util/intersection_tests';\nimport { getMaximumPaintValue, translateDistance, translate } from '../query_utils';\nimport properties from './line_style_layer_properties';\nimport { extend } from '../../util/util';\nimport EvaluationParameters from '../evaluation_parameters';\nimport renderColorRamp from '../../util/color_ramp';\nimport { Transitionable, Transitioning, Layout, PossiblyEvaluated, DataDrivenProperty } from '../properties';\n\nimport type { FeatureState } from '../../style-spec/expression';\nimport type {Bucket, BucketParameters} from '../../data/bucket';\nimport type {LayoutProps, PaintProps} from './line_style_layer_properties';\nimport type Transform from '../../geo/transform';\nimport type Texture from '../../render/texture';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass 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\nconst lineFloorwidthProperty = new LineFloorwidthProperty(properties.paint.properties['line-width'].specification);\nlineFloorwidthProperty.useIntegerZoom = true;\n\nclass LineStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout;\n layout: PossiblyEvaluated;\n\n gradient: ?RGBAImage;\n gradientTexture: ?Texture;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n _handleSpecialPaintPropertyUpdate(name: string) {\n if (name === 'line-gradient') {\n this._updateGradient();\n }\n }\n\n _updateGradient() {\n const expression = this._transitionablePaint._values['line-gradient'].value.expression;\n this.gradient = renderColorRamp(expression, 'lineProgress');\n this.gradientTexture = null;\n }\n\n recalculate(parameters: EvaluationParameters) {\n super.recalculate(parameters);\n\n (this.paint._values: 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: 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(queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number): 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\nexport default LineStyleLayer;\n\nfunction getLineWidth(lineWidth, lineGapWidth) {\n if (lineGapWidth > 0) {\n return lineGapWidth + 2 * lineWidth;\n } else {\n return lineWidth;\n }\n}\n\nfunction offsetLine(rings, offset) {\n const newRings = [];\n const zero = new Point(0, 0);\n for (let k = 0; k < rings.length; k++) {\n const ring = rings[k];\n const newRing = [];\n for (let i = 0; i < ring.length; i++) {\n const a = ring[i - 1];\n const b = ring[i];\n const c = ring[i + 1];\n const aToB = i === 0 ? zero : b.sub(a)._unit()._perp();\n const bToC = i === ring.length - 1 ? zero : 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 extrude._mult(1 / cosHalfAngle);\n\n newRing.push(extrude._mult(offset)._add(b));\n }\n newRings.push(newRing);\n }\n return newRings;\n}\n","// @flow\n\nimport { 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]);\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]);\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 // collision circles for lines store their distance to the anchor in tile units\n // so that they can be ignored if the projected label doesn't extend into\n // the box area\n { type: 'Int16', name: 'radius' },\n { type: 'Int16', name: 'signedDistanceFromAnchor' }\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: 'Int16'},\n {name: 'a_anchor_pos', components: 2, type: 'Int16'},\n {name: 'a_extrude', components: 2, type: 'Int16'}\n], 4);\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]);\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: '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: 'featureIndex' },\n { type: 'Uint16', name: 'numHorizontalGlyphVertices' },\n { type: 'Uint16', name: 'numVerticalGlyphVertices' },\n { type: 'Uint16', name: 'numIconVertices' },\n { type: 'Uint32', name: 'crossTileID' },\n { type: 'Float32', name: 'textBoxScale'},\n { type: 'Float32', name: 'radialTextOffset'}\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","// @flow\n\nimport { plugin as rtlTextPlugin } from '../source/rtl_text_plugin';\n\nimport type SymbolStyleLayer from '../style/style_layer/symbol_style_layer';\nimport type {Feature} from '../style-spec/expression';\nimport Formatted from '../style-spec/expression/types/formatted';\n\nfunction transformText(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 (rtlTextPlugin.applyArabicShaping) {\n text = rtlTextPlugin.applyArabicShaping(text);\n }\n\n return text;\n}\n\nexport default function(text: Formatted, layer: SymbolStyleLayer, feature: Feature): Formatted {\n text.sections.forEach(section => {\n section.text = transformText(section.text, layer, feature);\n });\n return text;\n}\n","// @flow\n\nimport {\n charHasRotatedVerticalOrientation,\n} 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 default 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","// @flow\n\nimport {\n charHasUprightVerticalOrientation,\n charAllowsIdeographicBreaking,\n charInComplexShapingScript\n} from '../util/script_detection';\nimport verticalizePunctuation from '../util/verticalize_punctuation';\nimport { plugin as rtlTextPlugin } from '../source/rtl_text_plugin';\nimport ONE_EM from './one_em';\n\nimport type {StyleGlyph} from '../style/style_glyph';\nimport type {ImagePosition} from '../render/image_atlas';\nimport Formatted from '../style-spec/expression/types/formatted';\n\nconst WritingMode = {\n horizontal: 1,\n vertical: 2,\n horizontalOnly: 3\n};\n\nexport { shapeText, shapeIcon, getAnchorAlignment, WritingMode };\n\n// The position of a glyph relative to the text's anchor point.\nexport type PositionedGlyph = {\n glyph: number,\n x: number,\n y: number,\n vertical: boolean,\n scale: number,\n fontStack: string,\n sectionIndex: number\n};\n\n// A collection of positioned glyphs and some metadata\nexport type Shaping = {\n positionedGlyphs: Array,\n top: number,\n bottom: number,\n left: number,\n right: number,\n writingMode: 1 | 2,\n lineCount: number,\n text: string,\n yOffset: number,\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\nclass TaggedString {\n text: string;\n sectionIndex: Array // maps each character in 'text' to its corresponding entry in 'sections'\n sections: Array<{ scale: number, fontStack: string }>\n\n constructor() {\n this.text = \"\";\n this.sectionIndex = [];\n this.sections = [];\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 result.sections.push({\n scale: section.scale || 1,\n fontStack: section.fontStack || defaultFontStack\n });\n result.text += section.text;\n for (let j = 0; j < section.text.length; j++) {\n result.sectionIndex.push(i);\n }\n }\n return result;\n }\n\n length(): number {\n return this.text.length;\n }\n\n getSection(index: number): { scale: number, fontStack: string } {\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\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(text: Formatted,\n glyphs: {[string]: {[number]: ?StyleGlyph}},\n defaultFontStack: string,\n maxWidth: number,\n lineHeight: number,\n textAnchor: SymbolAnchor,\n textJustify: TextJustify,\n spacing: number,\n translate: [number, number],\n writingMode: 1 | 2,\n allowVerticalPlacement: boolean): 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} = rtlTextPlugin;\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, glyphs));\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, glyphs));\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, glyphs));\n }\n\n const positionedGlyphs = [];\n const shaping = {\n positionedGlyphs,\n text: logicalInput.toString(),\n top: translate[1],\n bottom: translate[1],\n left: translate[0],\n right: translate[0],\n writingMode,\n lineCount: lines.length,\n yOffset: -17 // the y offset *should* be part of the font metadata\n };\n\n shapeLines(shaping, glyphs, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement);\n if (!positionedGlyphs.length) 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: {[number]: boolean} = {\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: {[number]: boolean} = {\n [0x0a]: true, // newline\n [0x20]: true, // space\n [0x26]: true, // ampersand\n [0x28]: true, // left parenthesis\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\nfunction determineAverageLineWidth(logicalInput: TaggedString,\n spacing: number,\n maxWidth: number,\n glyphMap: {[string]: {[number]: ?StyleGlyph}}) {\n let totalWidth = 0;\n\n for (let index = 0; index < logicalInput.length(); index++) {\n const section = logicalInput.getSection(index);\n const positions = glyphMap[section.fontStack];\n const glyph = positions && positions[logicalInput.getCharCode(index)];\n if (!glyph)\n continue;\n totalWidth += glyph.metrics.advance * section.scale + spacing;\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(breakIndex: number,\n breakX: number,\n targetWidth: number,\n potentialBreaks: Array,\n penalty: number,\n isLastBreak: boolean): 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): Array {\n if (!lastLineBreak) {\n return [];\n }\n return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index);\n}\n\nfunction determineLineBreaks(logicalInput: TaggedString,\n spacing: number,\n maxWidth: number,\n glyphMap: {[string]: {[number]: ?StyleGlyph}}): Array {\n if (!maxWidth)\n return [];\n\n if (!logicalInput)\n return [];\n\n const potentialLineBreaks = [];\n const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap);\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 const positions = glyphMap[section.fontStack];\n const glyph = positions && positions[codePoint];\n\n if (glyph && !whitespace[codePoint])\n currentX += glyph.metrics.advance * section.scale + spacing;\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) {\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: {[string]: {[number]: ?StyleGlyph}},\n lines: Array,\n lineHeight: number,\n textAnchor: SymbolAnchor,\n textJustify: TextJustify,\n writingMode: 1 | 2,\n spacing: number,\n allowVerticalPlacement: boolean) {\n\n let x = 0;\n let y = shaping.yOffset;\n\n let maxLineLength = 0;\n const positionedGlyphs = shaping.positionedGlyphs;\n\n const justify =\n textJustify === 'right' ? 1 :\n textJustify === 'left' ? 0 : 0.5;\n\n for (const line of lines) {\n line.trim();\n\n const lineMaxScale = line.getMaxScale();\n\n if (!line.length()) {\n y += lineHeight; // Still need a line feed after empty line\n continue;\n }\n\n const lineStartIndex = positionedGlyphs.length;\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 // 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 const baselineOffset = (lineMaxScale - section.scale) * 24;\n const positions = glyphMap[section.fontStack];\n const glyph = positions && positions[codePoint];\n\n if (!glyph) continue;\n\n if (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 ebabled, don't verticalize glyphs that\n // are from complex text layout script, or whitespaces.\n (allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)))) {\n positionedGlyphs.push({glyph: codePoint, x, y: y + baselineOffset, vertical: false, scale: section.scale, fontStack: section.fontStack, sectionIndex});\n x += glyph.metrics.advance * section.scale + spacing;\n } else {\n positionedGlyphs.push({glyph: codePoint, x, y: y + baselineOffset, vertical: true, scale: section.scale, fontStack: section.fontStack, sectionIndex});\n x += ONE_EM * section.scale + spacing;\n }\n }\n\n // Only justify if we placed at least one glyph\n if (positionedGlyphs.length !== lineStartIndex) {\n const lineLength = x - spacing;\n maxLineLength = Math.max(lineLength, maxLineLength);\n\n justifyLine(positionedGlyphs, glyphMap, lineStartIndex, positionedGlyphs.length - 1, justify);\n }\n\n x = 0;\n y += lineHeight * lineMaxScale;\n }\n\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(textAnchor);\n align(positionedGlyphs, justify, horizontalAlign, verticalAlign, maxLineLength, lineHeight, lines.length);\n\n // Calculate the bounding box\n const height = y - shaping.yOffset;\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 glyphMap: {[string]: {[number]: ?StyleGlyph}},\n start: number,\n end: number,\n justify: 1 | 0 | 0.5) {\n if (!justify)\n return;\n\n const lastPositionedGlyph = positionedGlyphs[end];\n const positions = glyphMap[lastPositionedGlyph.fontStack];\n const glyph = positions && positions[lastPositionedGlyph.glyph];\n if (glyph) {\n const lastAdvance = glyph.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 }\n }\n}\n\nfunction align(positionedGlyphs: Array,\n justify: number,\n horizontalAlign: number,\n verticalAlign: number,\n maxLineLength: number,\n lineHeight: number,\n lineCount: number) {\n const shiftX = (justify - horizontalAlign) * maxLineLength;\n const shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight;\n\n for (let j = 0; j < positionedGlyphs.length; j++) {\n positionedGlyphs[j].x += shiftX;\n positionedGlyphs[j].y += shiftY;\n }\n}\n\nexport type PositionedIcon = {\n image: ImagePosition,\n top: number,\n bottom: number,\n left: number,\n right: number\n};\n\nfunction shapeIcon(image: ImagePosition, iconOffset: [number, number], iconAnchor: SymbolAnchor): 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","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport { register } from '../util/web_worker_transfer';\n\nclass Anchor extends Point {\n angle: any;\n segment: number | void;\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\nexport default Anchor;\n","// @flow\n\nimport { number as interpolate } from '../style-spec/util/interpolate';\nimport Interpolate from '../style-spec/expression/definitions/interpolate';\nimport { clamp } from '../util/util';\nimport EvaluationParameters from '../style/evaluation_parameters';\n\nimport type {PropertyValue, PossiblyEvaluatedPropertyValue} from '../style/properties';\nimport type {InterpolationType} from '../style-spec/expression/definitions/interpolate';\n\nconst SIZE_PACK_FACTOR = 256;\n\nexport { getSizeData, evaluateSizeForFeature, evaluateSizeForZoom, SIZE_PACK_FACTOR };\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\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(tileZoom: number, value: PropertyValue>): 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 {uSize, uSizeT}: { uSize: number, uSizeT: number },\n {lowerSize, upperSize}: { lowerSize: number, upperSize: number}) {\n if (sizeData.kind === 'source') {\n return lowerSize / SIZE_PACK_FACTOR;\n } else if (sizeData.kind === 'composite') {\n return interpolate(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT);\n }\n return uSize;\n}\n\nfunction evaluateSizeForZoom(sizeData: SizeData, zoom: number) {\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 = interpolate(sizeData.minSize, sizeData.maxSize, t);\n } else {\n uSizeT = t;\n }\n }\n\n return {uSizeT, uSize};\n}\n","// @flow\n\nimport { symbolLayoutAttributes,\n collisionVertexAttributes,\n collisionBoxLayout,\n collisionCircleLayout,\n dynamicLayoutAttributes\n} from './symbol_attributes';\n\nimport { SymbolLayoutArray,\n SymbolDynamicLayoutArray,\n SymbolOpacityArray,\n CollisionBoxLayoutArray,\n CollisionCircleLayoutArray,\n CollisionVertexArray,\n PlacedSymbolArray,\n SymbolInstanceArray,\n GlyphOffsetArray,\n SymbolLineVertexArray\n} from '../array_types';\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/mergelines';\nimport {allowsVerticalWritingMode} from '../../util/script_detection';\nimport { WritingMode } from '../../symbol/shaping';\nimport loadGeometry from '../load_geometry';\nimport mvt from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = mvt.VectorTileFeature.types;\nimport {verticalizedCharacterMap} from '../../util/verticalize_punctuation';\nimport Anchor from '../../symbol/anchor';\nimport { getSizeData } from '../../symbol/symbol_size';\nimport { register } from '../../util/web_worker_transfer';\nimport EvaluationParameters from '../../style/evaluation_parameters';\nimport Formatted from '../../style-spec/expression/types/formatted';\n\nimport type {\n Bucket,\n BucketParameters,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\nimport type {CollisionBoxArray, CollisionBox, SymbolInstance} from '../array_types';\nimport type { StructArray, StructArrayMember } from '../../util/struct_array';\nimport 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';\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 textCircles?: Array;\n textFeatureIndex?: number;\n verticalTextFeatureIndex?: number;\n iconFeatureIndex?: number;\n};\n\nexport type SymbolFeature = {|\n sortKey: number | void,\n text: Formatted | void,\n icon: string | void,\n index: number,\n sourceLayerIndex: number,\n geometry: Array>,\n properties: Object,\n type: 'Point' | 'LineString' | 'Polygon',\n id?: any\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', offset: 0 }\n];\n\nfunction addVertex(array, anchorX, anchorY, ox, oy, tx, ty, sizeVertex) {\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 sizeVertex ? sizeVertex[0] : 0,\n sizeVertex ? sizeVertex[1] : 0\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\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\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.placedSymbolArray = new PlacedSymbolArray();\n }\n\n upload(context: Context, dynamicIndexBuffer: boolean, upload?: boolean, update?: boolean) {\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: Class,\n layoutAttributes: Array,\n IndexArray: Class) {\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 * 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.collisionBox`: Debug SymbolBuffers for collision boxes\n * `this.collisionCircle`: Debug SymbolBuffers for collision circles\n * The results are sent to the foreground for rendering\n *\n * 4. performSymbolPlacement(bucket, collisionIndex) 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 *\n * @private\n */\nclass 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 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 collisionArrays: Array;\n pixelRatio: number;\n tilePixelRatio: number;\n compareText: {[string]: Array};\n fadeStartTime: number;\n sortFeaturesByKey: boolean;\n sortFeaturesByY: boolean;\n sortedAngle: number;\n featureSortOrder: Array;\n\n text: SymbolBuffers;\n icon: SymbolBuffers;\n collisionBox: CollisionBuffers;\n collisionCircle: CollisionBuffers;\n uploaded: boolean;\n sourceLayerIndex: number;\n sourceID: string;\n symbolInstanceIndexes: Array;\n writingModes: Array;\n allowVerticalPlacement: boolean;\n hasPaintOverrides: 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.hasPaintOverrides = false;\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.sortFeaturesByKey = zOrder !== 'viewport-y' && sortKey.constantOr(1) !== undefined;\n const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey);\n this.sortFeaturesByY = zOrderByViewportY && (layout.get('text-allow-overlap') || layout.get('icon-allow-overlap') ||\n layout.get('text-ignore-placement') || layout.get('icon-ignore-placement'));\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 const layout = this.layers[0].layout;\n this.hasPaintOverrides = SymbolStyleLayer.hasPaintOverrides(layout);\n\n this.text = new SymbolBuffers(new ProgramConfigurationSet(symbolLayoutAttributes.members, this.layers, this.zoom, property => /^text/.test(property)));\n this.icon = new SymbolBuffers(new ProgramConfigurationSet(symbolLayoutAttributes.members, this.layers, this.zoom, property => /^icon/.test(property)));\n\n this.collisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);\n this.collisionCircle = new CollisionBuffers(CollisionCircleLayoutArray, collisionCircleLayout.members, TriangleIndexArray);\n\n this.glyphOffsetArray = new GlyphOffsetArray();\n this.lineVertexArray = new SymbolLineVertexArray();\n this.symbolInstances = new SymbolInstanceArray();\n }\n\n calculateGlyphDependencies(text: string, stack: {[number]: boolean}, textAlongLine: boolean, allowVerticalPlacement: boolean, doesAllowVerticalWritingMode: boolean) {\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) {\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' || textField.value.value.toString().length > 0) &&\n (textFont.value.kind !== 'constant' || textFont.value.value.length > 0);\n const hasIcon = iconImage.value.kind !== 'constant' || iconImage.value.value && iconImage.value.value.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 globalProperties = new EvaluationParameters(this.zoom);\n\n for (const {feature, index, sourceLayerIndex} of features) {\n if (!layer._featureFilter(globalProperties, feature)) {\n continue;\n }\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', feature);\n text = transformText(resolvedTokens instanceof Formatted ?\n resolvedTokens :\n Formatted.fromString(resolvedTokens),\n layer, feature);\n }\n\n let icon;\n if (hasIcon) {\n icon = layer.getValueAndResolveTokens('icon-image', feature);\n }\n\n if (!text && !icon) {\n continue;\n }\n\n const sortKey = this.sortFeaturesByKey ?\n symbolSortKey.evaluate(feature, {}) :\n undefined;\n\n const symbolFeature: SymbolFeature = {\n text,\n icon,\n index,\n sourceLayerIndex,\n geometry: loadGeometry(feature),\n properties: feature.properties,\n type: vectorTileFeatureTypes[feature.type],\n sortKey\n };\n if (typeof feature.id !== 'undefined') {\n symbolFeature.id = feature.id;\n }\n this.features.push(symbolFeature);\n\n if (icon) {\n icons[icon] = true;\n }\n\n if (text) {\n const fontStack = textFont.evaluate(feature, {}).join(',');\n const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point';\n this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(WritingMode.vertical) >= 0;\n for (const section of text.sections) {\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 }\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: any): number) - ((b.sortKey: any): 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 return this.symbolInstances.length === 0;\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) {\n this.collisionBox.upload(context);\n this.collisionCircle.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 destroy() {\n this.text.destroy();\n this.icon.destroy();\n this.collisionBox.destroy();\n this.collisionCircle.destroy();\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: any,\n labelAnchor: Anchor,\n lineStartIndex: number,\n lineLength: number) {\n const indexArray = arrays.indexArray;\n const layoutVertexArray = arrays.layoutVertexArray;\n const dynamicLayoutVertexArray = arrays.dynamicLayoutVertexArray;\n\n const segment = arrays.segments.prepareSegment(4 * quads.length, arrays.layoutVertexArray, arrays.indexArray, feature.sortKey);\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 addSymbol = (symbol: SymbolQuad) => {\n const tl = symbol.tl,\n tr = symbol.tr,\n bl = symbol.bl,\n br = symbol.br,\n tex = symbol.tex;\n\n const index = segment.vertexLength;\n\n const y = symbol.glyphOffset[1];\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex);\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex);\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex);\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex);\n\n addDynamicAttributes(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(symbol.glyphOffset[0]);\n };\n\n if (feature.text && feature.text.sections) {\n const sections = feature.text.sections;\n\n if (this.hasPaintOverrides) {\n let currentSectionIndex;\n const populatePaintArrayForSection = (sectionIndex?: number, lastSection: boolean) => {\n if (currentSectionIndex !== undefined && (currentSectionIndex !== sectionIndex || lastSection)) {\n arrays.programConfigurations.populatePaintArrays(arrays.layoutVertexArray.length, feature, feature.index, {}, sections[currentSectionIndex]);\n }\n currentSectionIndex = sectionIndex;\n };\n\n for (const symbol of quads) {\n populatePaintArrayForSection(symbol.sectionIndex, false);\n addSymbol(symbol);\n }\n\n // Populate paint arrays for the last section.\n populatePaintArrayForSection(currentSectionIndex, true);\n } else {\n for (const symbol of quads) {\n addSymbol(symbol);\n }\n arrays.programConfigurations.populatePaintArrays(arrays.layoutVertexArray.length, feature, feature.index, {}, sections[0]);\n }\n\n } else {\n for (const symbol of quads) {\n addSymbol(symbol);\n }\n arrays.programConfigurations.populatePaintArrays(arrays.layoutVertexArray.length, feature, feature.index, {});\n }\n\n arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y,\n glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex,\n lineStartIndex, lineLength, (labelAnchor.segment: any),\n sizeVertex ? sizeVertex[0] : 0, 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: any),\n // The crossTileID is only filled/used on the foreground for dynamic text anchors\n 0);\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, isCircle: boolean) {\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 if (isCircle) {\n const indexArray: TriangleIndexArray = (arrays.indexArray: any);\n indexArray.emplaceBack(index, index + 1, index + 2);\n indexArray.emplaceBack(index, index + 2, index + 3);\n\n segment.primitiveLength += 2;\n } else {\n const indexArray: LineIndexArray = (arrays.indexArray: any);\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\n addDebugCollisionBoxes(startIndex: number, endIndex: number, symbolInstance: SymbolInstance) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = (this.collisionBoxArray.get(b): any);\n const x1 = box.x1;\n const y1 = box.y1;\n const x2 = box.x2;\n const y2 = box.y2;\n\n // If the radius > 0, this collision box is actually a circle\n // The data we add to the buffers is exactly the same, but we'll render with a different shader.\n const isCircle = box.radius > 0;\n this.addCollisionDebugVertices(x1, y1, x2, y2, isCircle ? this.collisionCircle : this.collisionBox, box.anchorPoint, symbolInstance, isCircle);\n }\n }\n\n generateCollisionDebugBuffers() {\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);\n this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance);\n this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance);\n }\n }\n\n // These flat arrays are meant to be quicker to iterate over than the source\n // CollisionBoxArray\n _deserializeCollisionBoxesForSymbol(collisionBoxArray: CollisionBoxArray, textStartIndex: number, textEndIndex: number, verticalTextStartIndex: number, verticalTextEndIndex: number, iconStartIndex: number, iconEndIndex: number): CollisionArrays {\n const collisionArrays = {};\n for (let k = textStartIndex; k < textEndIndex; k++) {\n const box: CollisionBox = (collisionBoxArray.get(k): any);\n if (box.radius === 0) {\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 } else {\n if (!collisionArrays.textCircles) {\n collisionArrays.textCircles = [];\n collisionArrays.textFeatureIndex = box.featureIndex;\n }\n const used = 1; // May be updated at collision detection time\n collisionArrays.textCircles.push(box.anchorPointX, box.anchorPointY, box.radius, box.signedDistanceFromAnchor, used);\n }\n }\n for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) {\n const box: CollisionBox = (collisionBoxArray.get(k): any);\n if (box.radius === 0) {\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 }\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): any);\n if (box.radius === 0) {\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 }\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 ));\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 hasCollisionBoxData() {\n return this.collisionBox.segments.get().length > 0;\n }\n\n hasCollisionCircleData() {\n return this.collisionCircle.segments.get().length > 0;\n }\n\n addIndicesForPlacedTextSymbol(placedTextSymbolIndex: number) {\n const placedSymbol = this.text.placedSymbolArray.get(placedTextSymbolIndex);\n\n const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4;\n for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) {\n this.text.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2);\n this.text.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 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.addIndicesForPlacedTextSymbol(index);\n }\n });\n\n if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {\n this.addIndicesForPlacedTextSymbol(symbolInstance.verticalPlacedTextSymbolIndex);\n }\n\n const placedIcon = this.icon.placedSymbolArray.get(i);\n if (placedIcon.numGlyphs) {\n const vertexIndex = placedIcon.vertexStartIndex;\n this.icon.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2);\n this.icon.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3);\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 default SymbolBucket;\nexport { addDynamicAttributes };\n","// @flow\n\nimport type {SymbolFeature} from '../data/bucket/symbol_bucket';\n\nexport default function (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: any);\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.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport {\n ColorType\n} from '../../style-spec/expression/types';\n\nexport type LayoutProps = {|\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-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\": DataConstantProperty,\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\" | \"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-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-ignore-placement\": DataConstantProperty,\n \"text-optional\": DataConstantProperty,\n|};\n\nconst layout: Properties = new Properties({\n \"symbol-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-placement\"]),\n \"symbol-spacing\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-spacing\"]),\n \"symbol-avoid-edges\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-avoid-edges\"]),\n \"symbol-sort-key\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"symbol-sort-key\"]),\n \"symbol-z-order\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-z-order\"]),\n \"icon-allow-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-allow-overlap\"]),\n \"icon-ignore-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-ignore-placement\"]),\n \"icon-optional\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-optional\"]),\n \"icon-rotation-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-rotation-alignment\"]),\n \"icon-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-size\"]),\n \"icon-text-fit\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit\"]),\n \"icon-text-fit-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit-padding\"]),\n \"icon-image\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-image\"]),\n \"icon-rotate\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-rotate\"]),\n \"icon-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-padding\"]),\n \"icon-keep-upright\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-keep-upright\"]),\n \"icon-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-offset\"]),\n \"icon-anchor\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-anchor\"]),\n \"icon-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-pitch-alignment\"]),\n \"text-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-pitch-alignment\"]),\n \"text-rotation-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-rotation-alignment\"]),\n \"text-field\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-field\"]),\n \"text-font\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-font\"]),\n \"text-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-size\"]),\n \"text-max-width\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-max-width\"]),\n \"text-line-height\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-line-height\"]),\n \"text-letter-spacing\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-letter-spacing\"]),\n \"text-justify\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-justify\"]),\n \"text-radial-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-radial-offset\"]),\n \"text-variable-anchor\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-variable-anchor\"]),\n \"text-anchor\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-anchor\"]),\n \"text-max-angle\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-max-angle\"]),\n \"text-writing-mode\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-writing-mode\"]),\n \"text-rotate\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-rotate\"]),\n \"text-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-padding\"]),\n \"text-keep-upright\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-keep-upright\"]),\n \"text-transform\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-transform\"]),\n \"text-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-offset\"]),\n \"text-allow-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-allow-overlap\"]),\n \"text-ignore-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-ignore-placement\"]),\n \"text-optional\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-optional\"]),\n});\n\nexport type PaintProps = {|\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\nconst paint: Properties = new Properties({\n \"icon-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-opacity\"]),\n \"icon-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-color\"]),\n \"icon-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-color\"]),\n \"icon-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-width\"]),\n \"icon-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-blur\"]),\n \"icon-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate\"]),\n \"icon-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate-anchor\"]),\n \"text-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-opacity\"]),\n \"text-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-color\"], { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }),\n \"text-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-color\"]),\n \"text-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-width\"]),\n \"text-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-blur\"]),\n \"text-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate\"]),\n \"text-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate-anchor\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties, layout: Properties\n}>);\n","// @flow\n\nimport assert from 'assert';\nimport type { Expression } from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type { Value } from '../values';\nimport type { Type } from '../types';\nimport type { ZoomConstantExpression } from '../../expression';\nimport { NullType } from '../types';\nimport { PossiblyEvaluatedPropertyValue } from '../../../style/properties';\nimport { register } from '../../../util/web_worker_transfer';\n\nexport default class FormatSectionOverride implements Expression {\n type: Type;\n defaultValue: PossiblyEvaluatedPropertyValue;\n\n constructor(defaultValue: PossiblyEvaluatedPropertyValue) {\n assert(defaultValue.property.overrides !== undefined);\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): any);\n fn(expr._styleExpression.expression);\n }\n }\n\n // Cannot be statically evaluated, as the output depends on the evaluation context.\n possibleOutputs(): Array {\n return [undefined];\n }\n\n serialize() {\n return null;\n }\n}\n\nregister('FormatSectionOverride', FormatSectionOverride, {omit: ['defaultValue']});\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport assert from 'assert';\nimport SymbolBucket from '../../data/bucket/symbol_bucket';\nimport resolveTokens from '../../util/resolve_tokens';\nimport properties from './symbol_style_layer_properties';\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} from '../../style-spec/expression';\n\nimport type {BucketParameters} from '../../data/bucket';\nimport type {LayoutProps, PaintProps} from './symbol_style_layer_properties';\nimport type EvaluationParameters from '../evaluation_parameters';\nimport type {LayerSpecification} from '../../style-spec/types';\nimport type { Feature, SourceExpression, CompositeExpression } from '../../style-spec/expression';\nimport type {Expression} from '../../style-spec/expression/expression';\nimport {FormattedType} from '../../style-spec/expression/types';\nimport {typeOf} from '../../style-spec/expression/values';\nimport Formatted from '../../style-spec/expression/types/formatted';\nimport FormatSectionOverride from '../../style-spec/expression/definitions/format_section_override';\nimport FormatExpression from '../../style-spec/expression/definitions/format';\nimport Literal from '../../style-spec/expression/definitions/literal';\n\nclass 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) {\n super.recalculate(parameters);\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');\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: *, feature: Feature) {\n const value = this.layout.get(name).evaluate(feature, {});\n const unevaluated = this._unevaluatedLayout._values[name];\n if (!unevaluated.isDataDriven() && !isExpression(unevaluated.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 assert(false); // Should take a different path in FeatureIndex\n return false;\n }\n\n _setPaintOverrides() {\n for (const overridable of properties.paint.overridableProperties) {\n if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) {\n continue;\n }\n const overriden = this.paint.get(overridable);\n const override = new FormatSectionOverride(overriden);\n const styleExpression = new StyleExpression(override, overriden.property.specification);\n let expression = null;\n if (overriden.value.kind === 'constant' || overriden.value.kind === 'source') {\n expression = (new ZoomConstantExpression('source', styleExpression): SourceExpression);\n } else {\n expression = (new ZoomDependentExpression('composite',\n styleExpression,\n overriden.value.zoomStops,\n overriden.value._interpolationType): CompositeExpression);\n }\n this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overriden.property,\n expression,\n overriden.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): 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): any);\n if (expr._styleExpression) {\n checkExpression(expr._styleExpression.expression);\n }\n }\n\n return hasOverrides;\n }\n\n static hasPaintOverrides(layout: PossiblyEvaluated): boolean {\n for (const overridable of properties.paint.overridableProperties) {\n if (SymbolStyleLayer.hasPaintOverride(layout, overridable)) {\n return true;\n }\n }\n return false;\n }\n}\n\nexport default SymbolStyleLayer;\n","// @flow\nexport default resolveTokens;\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 * @private\n */\nfunction resolveTokens(properties: {+[string]: mixed}, text: string): string {\n return text.replace(/{([^{}]+)}/g, (match, key: string) => {\n return key in properties ? String(properties[key]) : '';\n });\n}\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\n\nexport type PaintProps = {|\n \"background-color\": DataConstantProperty,\n \"background-pattern\": CrossFadedProperty,\n \"background-opacity\": DataConstantProperty,\n|};\n\nconst paint: Properties = new Properties({\n \"background-color\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-color\"]),\n \"background-pattern\": new CrossFadedProperty(styleSpec[\"paint_background\"][\"background-pattern\"]),\n \"background-opacity\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport properties from './background_style_layer_properties';\nimport { Transitionable, Transitioning, PossiblyEvaluated } from '../properties';\n\nimport type {PaintProps} from './background_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass BackgroundStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n}\n\nexport default BackgroundStyleLayer;\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\n\nexport type PaintProps = {|\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\nconst paint: Properties = new Properties({\n \"raster-opacity\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-opacity\"]),\n \"raster-hue-rotate\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-hue-rotate\"]),\n \"raster-brightness-min\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-min\"]),\n \"raster-brightness-max\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-max\"]),\n \"raster-saturation\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-saturation\"]),\n \"raster-contrast\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-contrast\"]),\n \"raster-resampling\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-resampling\"]),\n \"raster-fade-duration\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-fade-duration\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport properties from './raster_style_layer_properties';\nimport { Transitionable, Transitioning, PossiblyEvaluated } from '../properties';\n\nimport type {PaintProps} from './raster_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass RasterStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n}\n\nexport default RasterStyleLayer;\n","// @flow\n\nimport StyleLayer from '../style_layer';\nimport type Map from '../../ui/map';\nimport assert from 'assert';\n\ntype CustomRenderMethod = (gl: WebGLRenderingContext, matrix: Array) => 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 Map.event:webglcontextlost} and\n * {@link Map.event:webglcontextrestored}.\n *\n * The `renderingMode` property controls whether the layer is treated as a `\"2d\"` or `\"3d\"` map layer. Use:\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 * @interface CustomLayerInterface\n * @property {string} id A unique layer id.\n * @property {string} type The layer's type. Must be `\"custom\"`.\n * @property {string} renderingMode Either `\"2d\"` or `\"3d\"`. Defaults to `\"2d\"`.\n * @example\n * // Custom layer implemented as ES6 class\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 * gl_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', function() {\n * map.addLayer(new NullIslandLayer());\n * });\n */\n\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 * @function\n * @memberof CustomLayerInterface\n * @instance\n * @name onAdd\n * @param {Map} map The Map this custom layer was just added to.\n * @param {WebGLRenderingContext} gl The gl context for the map.\n */\n\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 * @function\n * @memberof CustomLayerInterface\n * @instance\n * @name onRemove\n * @param {Map} map The Map this custom layer was just added to.\n * @param {WebGLRenderingContext} gl The gl context for the map.\n */\n\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 * @function\n * @memberof CustomLayerInterface\n * @instance\n * @name prerender\n * @param {WebGLRenderingContext} gl The map's gl context.\n * @param {Array} matrix The map's camera matrix. It projects spherical mercator\n * coordinates to gl coordinates. The 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}.fromLatLng\n * can be used to project a `LngLat` to a mercator coordinate.\n */\n\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 * @function\n * @memberof CustomLayerInterface\n * @instance\n * @name render\n * @param {WebGLRenderingContext} gl The map's gl context.\n * @param {Array} matrix The map's camera matrix. It projects spherical mercator\n * coordinates to gl 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}.fromLatLng\n * can be used to project a `LngLat` to a mercator coordinate.\n */\nexport type CustomLayerInterface = {\n id: string,\n type: \"custom\",\n renderingMode: \"2d\" | \"3d\",\n render: CustomRenderMethod,\n prerender: ?CustomRenderMethod,\n onAdd: ?(map: Map, gl: WebGLRenderingContext) => void,\n onRemove: ?(map: Map, gl: WebGLRenderingContext) => 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\nclass 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() {}\n\n serialize() {\n assert(false, \"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\nexport default CustomStyleLayer;\n","// @flow\n\nimport circle from './style_layer/circle_style_layer';\nimport heatmap from './style_layer/heatmap_style_layer';\nimport hillshade from './style_layer/hillshade_style_layer';\nimport fill from './style_layer/fill_style_layer';\nimport fillExtrusion from './style_layer/fill_extrusion_style_layer';\nimport line from './style_layer/line_style_layer';\nimport symbol from './style_layer/symbol_style_layer';\nimport background from './style_layer/background_style_layer';\nimport raster from './style_layer/raster_style_layer';\nimport CustomStyleLayer from './style_layer/custom_style_layer';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer';\n\nimport type {LayerSpecification} from '../style-spec/types';\n\nconst subclasses = {\n circle,\n heatmap,\n hillshade,\n fill,\n 'fill-extrusion': fillExtrusion,\n line,\n symbol,\n background,\n raster\n};\n\nexport default function createStyleLayer(layer: LayerSpecification | CustomLayerInterface) {\n if (layer.type === 'custom') {\n return new CustomStyleLayer(layer);\n } else {\n return new subclasses[layer.type](layer);\n }\n}\n\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","// @flow\n\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 type ImageManager from './image_manager';\nimport type Texture from './texture';\n\nconst padding = 1;\n\ntype Rect = {\n x: number,\n y: number,\n w: number,\n h: number\n};\n\nexport class ImagePosition {\n paddedRect: Rect;\n pixelRatio: number;\n version: number;\n\n constructor(paddedRect: Rect, {pixelRatio, version}: StyleImage) {\n this.paddedRect = paddedRect;\n this.pixelRatio = pixelRatio;\n this.version = version;\n }\n\n get tl(): [number, number] {\n return [\n this.paddedRect.x + padding,\n this.paddedRect.y + padding\n ];\n }\n\n get br(): [number, number] {\n return [\n this.paddedRect.x + this.paddedRect.w - padding,\n this.paddedRect.y + this.paddedRect.h - 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 - padding * 2) / this.pixelRatio,\n (this.paddedRect.h - padding * 2) / this.pixelRatio\n ];\n }\n}\n\nexport default class ImageAtlas {\n image: RGBAImage;\n iconPositions: {[string]: ImagePosition};\n patternPositions: {[string]: ImagePosition};\n haveRenderCallbacks: Array;\n uploaded: ?boolean;\n\n constructor(icons: {[string]: StyleImage}, patterns: {[string]: StyleImage}) {\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 + padding, y: bin.y + 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 + padding,\n y = bin.y + 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 * padding,\n h: src.data.height + 2 * 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\n","// @flow\n\nimport window from '../util/window';\nconst { HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData } = window;\n\nimport type Context from '../gl/context';\nimport type {RGBAImage, AlphaImage} from '../util/image';\n\nexport type TextureFormat =\n | $PropertyType\n | $PropertyType;\nexport type TextureFilter =\n | $PropertyType\n | $PropertyType\n | $PropertyType;\nexport type TextureWrap =\n | $PropertyType\n | $PropertyType\n | $PropertyType;\n\ntype EmptyImage = {\n width: number,\n height: number,\n data: null\n}\n\nexport type TextureImage =\n | RGBAImage\n | AlphaImage\n | HTMLImageElement\n | HTMLCanvasElement\n | HTMLVideoElement\n | ImageData\n | EmptyImage;\n\nclass 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: ?{ premultiply?: boolean, useMipmap?: boolean }) {\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: ?{premultiply?: boolean, useMipmap?: boolean}, position?: { x: number, y: number }) {\n const {width, height} = image;\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) {\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.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) {\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.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) {\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: any);\n }\n}\n\nexport default Texture;\n","// @flow\n\nimport {RGBAImage} from '../util/image';\n\nimport type Map from '../ui/map';\n\nexport type StyleImage = {\n data: RGBAImage,\n pixelRatio: number,\n sdf: boolean,\n version: number,\n hasRenderCallback?: boolean,\n userImage?: StyleImageInterface\n};\n\nexport type StyleImageInterface = {\n width: number,\n height: number,\n data: Uint8Array | Uint8ClampedArray,\n render?: () => void,\n onAdd?: (map: Map, id: string) => void,\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\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 * @interface StyleImageInterface\n * @property {number} width\n * @property {number} height\n * @property {Uint8Array | Uint8ClampedArray} data\n *\n * @see [Add an animated icon to the map.](https://docs.mapbox.com/mapbox-gl-js/example/add-image-animated/)\n *\n * @example\n * var 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 * var 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 * var bytesPerPixel = 4;\n * for (var x = 0; x < this.width; x++) {\n * for (var y = 0; y < this.height; y++) {\n * var 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/**\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 * @function\n * @memberof StyleImageInterface\n * @instance\n * @name render\n * @return {boolean} `true` if this method updated the image. `false` if the image was not changed.\n */\n\n/**\n * Optional method called when the layer has been added to the Map with {@link Map#addImage}.\n *\n * @function\n * @memberof StyleImageInterface\n * @instance\n * @name onAdd\n * @param {Map} map The Map this custom layer was just added to.\n */\n\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 * @function\n * @memberof StyleImageInterface\n * @instance\n * @name onRemove\n */\n","// @flow\n\nimport potpack from 'potpack';\n\nimport { Event, Evented } from '../util/evented';\nimport { RGBAImage } from '../util/image';\nimport { ImagePosition } from './image_atlas';\nimport Texture from './texture';\nimport assert from 'assert';\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 {Bin} from 'potpack';\nimport type {Callback} from '../types/callback';\n\ntype Pattern = {\n bin: Bin,\n position: ImagePosition\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.\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*/\nclass ImageManager extends Evented {\n images: {[string]: StyleImage};\n updatedImages: {[string]: boolean};\n callbackDispatchedThisFrame: {[string]: boolean};\n loaded: boolean;\n requestors: Array<{ids: Array, callback: Callback<{[string]: StyleImage}>}>;\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, callback} of this.requestors) {\n this._notify(ids, callback);\n }\n this.requestors = [];\n }\n }\n\n getImage(id: string): ?StyleImage {\n return this.images[id];\n }\n\n addImage(id: string, image: StyleImage) {\n assert(!this.images[id]);\n this.images[id] = image;\n }\n\n updateImage(id: string, image: StyleImage) {\n const oldImage = this.images[id];\n assert(oldImage);\n assert(oldImage.data.width === image.data.width);\n assert(oldImage.data.height === image.data.height);\n image.version = oldImage.version + 1;\n this.images[id] = image;\n this.updatedImages[id] = true;\n }\n\n removeImage(id: string) {\n assert(this.images[id]);\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, callback: Callback<{[string]: StyleImage}>) {\n // If the sprite has been loaded, or if all the icon dependencies are already present\n // (i.e. if they've been addeded 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 this._notify(ids, callback);\n } else {\n this.requestors.push({ids, callback});\n }\n }\n\n _notify(ids: Array, callback: Callback<{[string]: StyleImage}>) {\n const response = {};\n\n for (const id of ids) {\n if (!this.images[id]) {\n this.fire(new Event('styleimagemissing', { id }));\n }\n const image = this.images[id];\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 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\n callback(null, 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.images[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.images[id];\n assert(image);\n\n const updated = renderStyleImage(image);\n if (updated) {\n this.updateImage(id, image);\n }\n }\n }\n}\n\nexport default ImageManager;\n","exports.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","'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\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 str = readUtf8(this.buf, this.pos, end);\n this.pos = end;\n return str;\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 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","// @flow\n\nimport { 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: Object, 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 default function (data: ArrayBuffer | Uint8Array): Array {\n return new Protobuf(data).readFields(readFontstacks, []);\n}\n\nexport const GLYPH_PBF_BORDER = border;\n","'use strict';\n\nmodule.exports = TinySDF;\nmodule.exports.default = TinySDF;\n\nvar INF = 1e20;\n\nfunction TinySDF(fontSize, buffer, radius, cutoff, fontFamily, fontWeight) {\n this.fontSize = fontSize || 24;\n this.buffer = buffer === undefined ? 3 : buffer;\n this.cutoff = cutoff || 0.25;\n this.fontFamily = fontFamily || 'sans-serif';\n this.fontWeight = fontWeight || 'normal';\n this.radius = radius || 8;\n var size = this.size = this.fontSize + this.buffer * 2;\n\n this.canvas = document.createElement('canvas');\n this.canvas.width = this.canvas.height = size;\n\n this.ctx = this.canvas.getContext('2d');\n this.ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily;\n this.ctx.textBaseline = 'middle';\n this.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.d = new Float64Array(size);\n this.z = new Float64Array(size + 1);\n this.v = new Int16Array(size);\n\n // hack around https://bugzilla.mozilla.org/show_bug.cgi?id=737852\n this.middle = Math.round((size / 2) * (navigator.userAgent.indexOf('Gecko/') >= 0 ? 1.2 : 1));\n}\n\nTinySDF.prototype.draw = function (char) {\n this.ctx.clearRect(0, 0, this.size, this.size);\n this.ctx.fillText(char, this.buffer, this.middle);\n\n var imgData = this.ctx.getImageData(0, 0, this.size, this.size);\n var alphaChannel = new Uint8ClampedArray(this.size * this.size);\n\n for (var i = 0; i < this.size * this.size; i++) {\n var a = imgData.data[i * 4 + 3] / 255; // alpha value\n this.gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2);\n this.gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2);\n }\n\n edt(this.gridOuter, this.size, this.size, this.f, this.d, this.v, this.z);\n edt(this.gridInner, this.size, this.size, this.f, this.d, this.v, this.z);\n\n for (i = 0; i < this.size * this.size; i++) {\n var d = this.gridOuter[i] - this.gridInner[i];\n alphaChannel[i] = Math.max(0, Math.min(255, Math.round(255 - 255 * (d / this.radius + this.cutoff))));\n }\n\n return alphaChannel;\n};\n\n// 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf\nfunction edt(data, width, height, f, d, v, z) {\n for (var x = 0; x < width; x++) {\n for (var y = 0; y < height; y++) {\n f[y] = data[y * width + x];\n }\n edt1d(f, d, v, z, height);\n for (y = 0; y < height; y++) {\n data[y * width + x] = d[y];\n }\n }\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n f[x] = data[y * width + x];\n }\n edt1d(f, d, v, z, width);\n for (x = 0; x < width; x++) {\n data[y * width + x] = Math.sqrt(d[x]);\n }\n }\n}\n\n// 1D squared distance transform\nfunction edt1d(f, d, v, z, n) {\n v[0] = 0;\n z[0] = -INF;\n z[1] = +INF;\n\n for (var q = 1, k = 0; q < n; q++) {\n var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);\n while (s <= z[k]) {\n k--;\n s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);\n }\n k++;\n v[k] = q;\n z[k] = s;\n z[k + 1] = +INF;\n }\n\n for (q = 0, k = 0; q < n; q++) {\n while (z[k + 1] < q) k++;\n d[q] = (q - v[k]) * (q - v[k]) + f[v[k]];\n }\n}\n","// @flow\n\nimport loadGlyphRange from '../style/load_glyph_range';\n\nimport TinySDF from '@mapbox/tiny-sdf';\nimport isChar from '../util/is_char_in_unicode_block';\nimport { asyncAll } from '../util/util';\nimport { AlphaImage } from '../util/image';\n\nimport type {StyleGlyph} from '../style/style_glyph';\nimport type {RequestManager} from '../util/mapbox';\nimport type {Callback} from '../types/callback';\n\ntype Entry = {\n // null means we've requested the range, but the glyph wasn't included in the result.\n glyphs: {[id: number]: StyleGlyph | null},\n requests: {[range: number]: Array>},\n tinySDF?: TinySDF\n};\n\nclass GlyphManager {\n requestManager: RequestManager;\n localIdeographFontFamily: ?string;\n entries: {[string]: Entry};\n url: ?string;\n\n // exposed as statics to enable stubbing in unit tests\n static loadGlyphRange: typeof loadGlyphRange;\n static TinySDF: Class;\n\n constructor(requestManager: RequestManager, localIdeographFontFamily: ?string) {\n this.requestManager = requestManager;\n this.localIdeographFontFamily = localIdeographFontFamily;\n this.entries = {};\n }\n\n setURL(url: ?string) {\n this.url = url;\n }\n\n getGlyphs(glyphs: {[stack: string]: Array}, callback: Callback<{[stack: string]: {[id: number]: ?StyleGlyph}}>) {\n const all = [];\n\n for (const stack in glyphs) {\n for (const id of glyphs[stack]) {\n all.push({stack, id});\n }\n }\n\n asyncAll(all, ({stack, id}, callback: Callback<{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 };\n }\n\n let glyph = entry.glyphs[id];\n if (glyph !== undefined) {\n callback(null, {stack, id, glyph});\n return;\n }\n\n glyph = this._tinySDF(entry, stack, id);\n if (glyph) {\n entry.glyphs[id] = glyph;\n callback(null, {stack, id, glyph});\n return;\n }\n\n const range = Math.floor(id / 256);\n if (range * 256 > 65535) {\n callback(new Error('glyphs > 65535 not supported'));\n return;\n }\n\n let requests = entry.requests[range];\n if (!requests) {\n requests = entry.requests[range] = [];\n GlyphManager.loadGlyphRange(stack, range, (this.url: any), this.requestManager,\n (err, response: ?{[number]: StyleGlyph | null}) => {\n if (response) {\n for (const id in response) {\n if (!this._doesCharSupportLocalGlyph(+id)) {\n entry.glyphs[+id] = response[+id];\n }\n }\n }\n for (const cb of requests) {\n cb(err, response);\n }\n delete entry.requests[range];\n });\n }\n\n requests.push((err, result: ?{[number]: StyleGlyph | null}) => {\n if (err) {\n callback(err);\n } else if (result) {\n callback(null, {stack, id, glyph: result[id] || null});\n }\n });\n }, (err, glyphs: ?Array<{stack: string, id: number, glyph: ?StyleGlyph}>) => {\n if (err) {\n callback(err);\n } else if (glyphs) {\n const result = {};\n\n for (const {stack, id, glyph} of glyphs) {\n // Clone the glyph so that our own copy of its ArrayBuffer doesn't get transferred.\n (result[stack] || (result[stack] = {}))[id] = glyph && {\n id: glyph.id,\n bitmap: glyph.bitmap.clone(),\n metrics: glyph.metrics\n };\n }\n\n callback(null, result);\n }\n });\n }\n\n _doesCharSupportLocalGlyph(id: number): boolean {\n /* eslint-disable new-cap */\n return !!this.localIdeographFontFamily &&\n (isChar['CJK Unified Ideographs'](id) ||\n isChar['Hangul Syllables'](id) ||\n isChar['Hiragana'](id) ||\n isChar['Katakana'](id));\n /* eslint-enable new-cap */\n }\n\n _tinySDF(entry: Entry, stack: string, id: number): ?StyleGlyph {\n const family = this.localIdeographFontFamily;\n if (!family) {\n return;\n }\n\n if (!this._doesCharSupportLocalGlyph(id)) {\n return;\n }\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(24, 3, 8, .25, family, fontWeight);\n }\n\n return {\n id,\n bitmap: new AlphaImage({width: 30, height: 30}, tinySDF.draw(String.fromCharCode(id))),\n metrics: {\n width: 24,\n height: 24,\n left: 0,\n top: -8,\n advance: 24\n }\n };\n }\n}\n\nGlyphManager.loadGlyphRange = loadGlyphRange;\nGlyphManager.TinySDF = TinySDF;\n\nexport default GlyphManager;\n","// @flow\n\nimport { getArrayBuffer, ResourceType } from '../util/ajax';\n\nimport parseGlyphPBF from './parse_glyph_pbf';\n\nimport type {StyleGlyph} from './style_glyph';\nimport type {RequestManager} from '../util/mapbox';\nimport type {Callback} from '../types/callback';\n\nexport default function (fontstack: string,\n range: number,\n urlTemplate: string,\n requestManager: RequestManager,\n callback: Callback<{[number]: StyleGlyph | null}>) {\n const begin = range * 256;\n const end = begin + 255;\n\n const request = requestManager.transformRequest(\n requestManager.normalizeGlyphsURL(urlTemplate)\n .replace('{fontstack}', fontstack)\n .replace('{range}', `${begin}-${end}`),\n ResourceType.Glyphs);\n\n getArrayBuffer(request, (err: ?Error, data: ?ArrayBuffer) => {\n if (err) {\n callback(err);\n } else if (data) {\n const glyphs = {};\n\n for (const glyph of parseGlyphPBF(data)) {\n glyphs[glyph.id] = glyph;\n }\n\n callback(null, glyphs);\n }\n });\n}\n","// @flow\n\nimport styleSpec from '../style-spec/reference/latest';\n\nimport { endsWith, extend, sphericalToCartesian } from '../util/util';\nimport { Evented } from '../util/evented';\nimport {\n validateStyle,\n validateLight,\n emitValidationErrors\n} from './validate_style';\nimport Color from '../style-spec/util/color';\nimport { number as interpolate } from '../style-spec/util/interpolate';\n\nimport type {StylePropertySpecification} from '../style-spec/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\nimport type {LightSpecification} from '../style-spec/types';\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;\n }\n\n possiblyEvaluate(value: PropertyValue<[number, number, number], LightPosition>, parameters: EvaluationParameters): LightPosition {\n return sphericalToCartesian(value.expression.evaluate(parameters));\n }\n\n interpolate(a: LightPosition, b: LightPosition, t: number): LightPosition {\n return {\n x: interpolate(a.x, b.x, t),\n y: interpolate(a.y, b.y, t),\n z: interpolate(a.z, b.z, t),\n };\n }\n}\n\ntype Props = {|\n \"anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"position\": LightPositionProperty,\n \"color\": DataConstantProperty,\n \"intensity\": DataConstantProperty,\n|};\n\nconst properties: Properties = new Properties({\n \"anchor\": new DataConstantProperty(styleSpec.light.anchor),\n \"position\": new LightPositionProperty(),\n \"color\": new DataConstantProperty(styleSpec.light.color),\n \"intensity\": new DataConstantProperty(styleSpec.light.intensity),\n});\n\nconst TRANSITION_SUFFIX = '-transition';\n\n/*\n * Represents the light used to light extruded features.\n */\nclass Light extends Evented {\n _transitionable: Transitionable;\n _transitioning: Transitioning;\n properties: PossiblyEvaluated;\n\n constructor(lightOptions?: LightSpecification) {\n super();\n this._transitionable = new Transitionable(properties);\n this.setLight(lightOptions);\n this._transitioning = this._transitionable.untransitioned();\n }\n\n getLight() {\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 (endsWith(name, TRANSITION_SUFFIX)) {\n this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value);\n } else {\n this._transitionable.setValue(name, 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: mixed, options?: {validate?: boolean}) {\n if (options && options.validate === false) {\n return false;\n }\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\nexport default Light;\n","// @flow\n\nimport { warnOnce } from '../util/util';\n\nimport type Context from '../gl/context';\n\n/**\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 .getDash.\n *\n * @param {number} width\n * @param {number} height\n * @private\n */\nclass LineAtlas {\n width: number;\n height: number;\n nextRow: number;\n bytes: number;\n data: Uint8Array;\n positions: {[string]: any};\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.bytes = 4;\n this.data = new Uint8Array(this.width * this.height * this.bytes);\n\n this.positions = {};\n }\n\n /**\n * Get or create a dash line pattern.\n *\n * @param {Array} dasharray\n * @param {boolean} round whether to add circle caps in between dash segments\n * @returns {Object} position of dash texture in { y, height, width }\n * @private\n */\n getDash(dasharray: Array, round: boolean) {\n const key = dasharray.join(\",\") + String(round);\n\n if (!this.positions[key]) {\n this.positions[key] = this.addDash(dasharray, round);\n }\n return this.positions[key];\n }\n\n addDash(dasharray: Array, round: boolean) {\n\n const n = round ? 7 : 0;\n const height = 2 * n + 1;\n const offset = 128;\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++) {\n length += dasharray[i];\n }\n\n const stretch = this.width / length;\n const halfWidth = stretch / 2;\n\n // If dasharray has an odd length, both the first and last parts\n // are dashes and should be joined seamlessly.\n const oddLength = dasharray.length % 2 === 1;\n\n for (let y = -n; y <= n; y++) {\n const row = this.nextRow + n + y;\n const index = this.width * row;\n\n let left = oddLength ? -dasharray[dasharray.length - 1] : 0;\n let right = dasharray[0];\n let partIndex = 1;\n\n for (let x = 0; x < this.width; x++) {\n\n while (right < x / stretch) {\n left = right;\n right = right + dasharray[partIndex];\n\n if (oddLength && partIndex === dasharray.length - 1) {\n right += dasharray[0];\n }\n\n partIndex++;\n }\n\n const distLeft = Math.abs(x - left * stretch);\n const distRight = Math.abs(x - right * stretch);\n const dist = Math.min(distLeft, distRight);\n const inside = (partIndex % 2) === 1;\n let signedDistance;\n\n if (round) {\n // Add circle caps\n const distMiddle = n ? y / n * (halfWidth + 1) : 0;\n if (inside) {\n const distEdge = halfWidth - Math.abs(distMiddle);\n signedDistance = Math.sqrt(dist * dist + distEdge * distEdge);\n } else {\n signedDistance = halfWidth - Math.sqrt(dist * dist + distMiddle * distMiddle);\n }\n } else {\n signedDistance = (inside ? 1 : -1) * dist;\n }\n\n this.data[3 + (index + x) * 4] = Math.max(0, Math.min(255, signedDistance + offset));\n }\n }\n\n const pos = {\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 pos;\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.RGBA, this.width, this.height, 0, gl.RGBA, 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.RGBA, gl.UNSIGNED_BYTE, this.data);\n }\n }\n }\n}\n\nexport default LineAtlas;\n","// @flow\n\n/**\n * Invokes the wrapped function in a non-blocking way when trigger() is called. Invocation requests\n * are ignored until the function was actually invoked.\n *\n * @private\n */\nclass ThrottledInvoker {\n _channel: MessageChannel;\n _triggered: boolean;\n _callback: Function\n\n constructor(callback: Function) {\n this._callback = callback;\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._callback();\n };\n }\n }\n\n trigger() {\n if (!this._triggered) {\n this._triggered = true;\n if (this._channel) {\n this._channel.port1.postMessage(true);\n } else {\n setTimeout(() => {\n this._triggered = false;\n this._callback();\n }, 0);\n }\n }\n }\n}\n\nexport default ThrottledInvoker;\n","// @flow\n\nimport { bindAll } from './util';\nimport { serialize, deserialize } from './web_worker_transfer';\nimport ThrottledInvoker from './throttled_invoker';\n\nimport type {Transferable} from '../types/transferable';\nimport type {Cancelable} from '../types/cancelable';\n\n/**\n * An implementation of the [Actor design pattern](http://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 *\n * @param {WebWorker} target\n * @param {WebWorker} parent\n * @param {string|number} mapId A unique identifier for the Map instance using this Actor.\n * @private\n */\nclass Actor {\n target: any;\n parent: any;\n mapId: ?number;\n callbacks: { number: any };\n name: string;\n tasks: { number: any };\n taskQueue: Array;\n cancelCallbacks: { number: Cancelable };\n invoker: ThrottledInvoker;\n\n constructor(target: any, parent: any, mapId: ?number) {\n this.target = target;\n this.parent = parent;\n this.mapId = mapId;\n this.callbacks = {};\n this.tasks = {};\n this.taskQueue = [];\n this.cancelCallbacks = {};\n bindAll(['receive', 'process'], this);\n this.invoker = new ThrottledInvoker(this.process);\n this.target.addEventListener('message', this.receive, false);\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 *\n * @param type The name of the target method to invoke or '[source-type].[source-name].name' for a method on a WorkerSource.\n * @param targetMapId A particular mapId to which to send this message.\n * @private\n */\n send(type: string, data: mixed, callback: ?Function, targetMapId: ?string): ?Cancelable {\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 if (callback) {\n this.callbacks[id] = callback;\n }\n const buffers: Array = [];\n this.target.postMessage({\n id,\n type,\n hasCallback: !!callback,\n targetMapId,\n sourceMapId: this.mapId,\n data: serialize(data, buffers)\n }, buffers);\n return {\n cancel: () => {\n if (callback) {\n // Set the callback to null so that it never fires after the request is aborted.\n delete this.callbacks[id];\n }\n this.target.postMessage({\n id,\n type: '',\n targetMapId,\n sourceMapId: this.mapId\n });\n }\n };\n }\n\n receive(message: Object) {\n const data = message.data,\n id = data.id;\n\n if (!id) {\n return;\n }\n\n if (data.targetMapId && this.mapId !== data.targetMapId) {\n return;\n }\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 cancel = this.cancelCallbacks[id];\n delete this.cancelCallbacks[id];\n if (cancel) {\n cancel();\n }\n } else {\n // 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 }\n }\n\n process() {\n if (!this.taskQueue.length) {\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) {\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 if (task.type === '') {\n // The done() function in the counterpart has been called, and we are now\n // firing the callback in the originating actor, if there is one.\n const callback = this.callbacks[id];\n delete this.callbacks[id];\n if (callback) {\n // If we get a response, but don't have a callback, the request was canceled.\n if (task.error) {\n callback(deserialize(task.error));\n } else {\n callback(null, deserialize(task.data));\n }\n }\n } else {\n let completed = false;\n const done = task.hasCallback ? (err, data) => {\n completed = true;\n delete this.cancelCallbacks[id];\n const buffers: Array = [];\n this.target.postMessage({\n id,\n type: '',\n sourceMapId: this.mapId,\n error: err ? serialize(err) : null,\n data: serialize(data, buffers)\n }, buffers);\n } : (_) => {\n completed = true;\n };\n\n let callback = null;\n const params = (deserialize(task.data): any);\n if (this.parent[task.type]) {\n // task.type == 'loadTile', 'removeTile', etc.\n callback = this.parent[task.type](task.sourceMapId, params, done);\n } else if (this.parent.getWorkerSource) {\n // task.type == sourcetype.method\n const keys = task.type.split('.');\n const scope = (this.parent: any).getWorkerSource(task.sourceMapId, keys[0], params.source);\n callback = scope[keys[1]](params, done);\n } else {\n // No function was found.\n done(new Error(`Could not find function ${task.type}`));\n }\n\n if (!completed && callback && callback.cancel) {\n // Allows canceling the task as long as it hasn't been completed yet.\n this.cancelCallbacks[id] = callback.cancel;\n }\n }\n }\n\n remove() {\n this.target.removeEventListener('message', this.receive, false);\n }\n}\n\nexport default Actor;\n","// @flow\n\nimport { uniqueId, asyncAll } from './util';\nimport Actor from './actor';\nimport assert from 'assert';\n\nimport type WorkerPool from './worker_pool';\n\n/**\n * Responsible for sending messages from a {@link Source} to an associated\n * {@link WorkerSource}.\n *\n * @private\n */\nclass Dispatcher {\n workerPool: WorkerPool;\n actors: Array;\n currentActor: number;\n id: number;\n\n // exposed to allow stubbing in unit tests\n static Actor: Class;\n\n constructor(workerPool: WorkerPool, parent: any) {\n this.workerPool = workerPool;\n this.actors = [];\n this.currentActor = 0;\n this.id = uniqueId();\n const workers = this.workerPool.acquire(this.id);\n for (let i = 0; i < workers.length; i++) {\n const worker = workers[i];\n const actor = new Dispatcher.Actor(worker, parent, this.id);\n actor.name = `Worker ${i}`;\n this.actors.push(actor);\n }\n assert(this.actors.length);\n }\n\n /**\n * Broadcast a message to all Workers.\n */\n broadcast(type: string, data: mixed, cb?: Function) {\n assert(this.actors.length);\n cb = cb || function () {};\n asyncAll(this.actors, (actor, done) => {\n actor.send(type, data, done);\n }, cb);\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 assert(this.actors.length);\n this.currentActor = (this.currentActor + 1) % this.actors.length;\n return this.actors[this.currentActor];\n }\n\n remove() {\n this.actors.forEach((actor) => { actor.remove(); });\n this.actors = [];\n this.workerPool.release(this.id);\n }\n}\n\nDispatcher.Actor = Actor;\n\nexport default Dispatcher;\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","// @flow\n\nimport LngLat from './lng_lat';\n\nimport type {LngLatLike} from './lng_lat';\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 * @param {LngLatLike} [sw] The southwest corner of the bounding box.\n * @param {LngLatLike} [ne] The northeast corner of the bounding box.\n * @example\n * var sw = new mapboxgl.LngLat(-73.9876, 40.7661);\n * var ne = new mapboxgl.LngLat(-73.9397, 40.8002);\n * var llb = new mapboxgl.LngLatBounds(sw, ne);\n */\nclass LngLatBounds {\n _ne: LngLat;\n _sw: LngLat;\n\n // This constructor is too flexible to type. It should not be so flexible.\n constructor(sw: any, ne: any) {\n if (!sw) {\n // noop\n } else if (ne) {\n this.setSouthWest(sw).setNorthEast(ne);\n } else if (sw.length === 4) {\n this.setSouthWest([sw[0], sw[1]]).setNorthEast([sw[2], sw[3]]);\n } else {\n this.setSouthWest(sw[0]).setNorthEast(sw[1]);\n }\n }\n\n /**\n * Set the northeast corner of the bounding box\n *\n * @param {LngLatLike} ne\n * @returns {LngLatBounds} `this`\n */\n setNorthEast(ne: LngLatLike) {\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 {LngLatLike} sw\n * @returns {LngLatBounds} `this`\n */\n setSouthWest(sw: LngLatLike) {\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 LngLat or LngLatBounds.\n *\n * @param {LngLat|LngLatBounds} obj object to extend to\n * @returns {LngLatBounds} `this`\n */\n extend(obj: LngLat | LngLatBounds) {\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.every(Array.isArray)) {\n return this.extend(LngLatBounds.convert(obj));\n } else {\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 {LngLat} The bounding box's center.\n * @example\n * var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315}\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 {LngLat} 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 {LngLat} 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 {LngLat} 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 {LngLat} 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 {number} 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 {number} 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 {number} 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 {number} 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 {Array>} 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 * var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]]\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 {string} The bounding box represents as a string of the format\n * `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`.\n * @example\n * var llb = new mapboxgl.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 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 {boolean} True if bounds have been defined, otherwise false.\n */\n isEmpty() {\n return !(this._sw && this._ne);\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 {LngLatBoundsLike} input An array of two coordinates to convert, or a `LngLatBounds` object to return.\n * @returns {LngLatBounds} A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object.\n * @example\n * var arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];\n * var llb = mapboxgl.LngLatBounds.convert(arr);\n * llb; // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}}\n */\n static convert(input: LngLatBoundsLike): LngLatBounds {\n if (!input || input instanceof LngLatBounds) return input;\n return new LngLatBounds(input);\n }\n}\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 * @typedef {LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number]} LngLatBoundsLike\n * @example\n * var v1 = new mapboxgl.LngLatBounds(\n * new mapboxgl.LngLat(-73.9876, 40.7661),\n * new mapboxgl.LngLat(-73.9397, 40.8002)\n * );\n * var v2 = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002])\n * var v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]];\n */\nexport type LngLatBoundsLike = LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number];\n\nexport default LngLatBounds;\n","// @flow\n\nimport { wrap } from '../util/util';\nimport LngLatBounds from './lng_lat_bounds';\n\n/**\n * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees.\n *\n * Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.\n *\n * Note that any Mapbox GL 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 * @param {number} lng Longitude, measured in degrees.\n * @param {number} lat Latitude, measured in degrees.\n * @example\n * var ll = new mapboxgl.LngLat(-73.9749, 40.7736);\n * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)\n * @see [Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/)\n * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n * @see [Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/)\n */\nclass LngLat {\n lng: number;\n lat: number;\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 {LngLat} The wrapped `LngLat` object.\n * @example\n * var ll = new mapboxgl.LngLat(286.0251, 40.7736);\n * var wrapped = ll.wrap();\n * wrapped.lng; // = -73.9749\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 {Array} The coordinates represeted as an array of longitude and latitude.\n * @example\n * var ll = new mapboxgl.LngLat(-73.9749, 40.7736);\n * ll.toArray(); // = [-73.9749, 40.7736]\n */\n toArray() {\n return [this.lng, this.lat];\n }\n\n /**\n * Returns the coordinates represent as a string.\n *\n * @returns {string} The coordinates represented as a string of the format `'LngLat(lng, lat)'`.\n * @example\n * var ll = new mapboxgl.LngLat(-73.9749, 40.7736);\n * ll.toString(); // = \"LngLat(-73.9749, 40.7736)\"\n */\n toString() {\n return `LngLat(${this.lng}, ${this.lat})`;\n }\n\n /**\n * Returns a `LngLatBounds` from the coordinates extended by a given `radius`.\n *\n * @param {number} [radius=0] Distance in meters from the coordinates to extend the bounds.\n * @returns {LngLatBounds} A new `LngLatBounds` object representing the coordinates extended by the `radius`.\n * @example\n * var ll = new mapboxgl.LngLat(-73.9749, 40.7736);\n * ll.toBounds(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]]\n */\n toBounds(radius?: number = 0) {\n const earthCircumferenceInMetersAtEquator = 40075017;\n const latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator,\n lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);\n\n return new LngLatBounds(new LngLat(this.lng - lngAccuracy, this.lat - latAccuracy),\n new LngLat(this.lng + lngAccuracy, this.lat + latAccuracy));\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 {LngLatLike} input An array of two numbers or object to convert, or a `LngLat` object to return.\n * @returns {LngLat} A new `LngLat` object, if a conversion occurred, or the original `LngLat` object.\n * @example\n * var arr = [-73.9749, 40.7736];\n * var ll = mapboxgl.LngLat.convert(arr);\n * ll; // = LngLat {lng: -73.9749, lat: 40.7736}\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: any).lng : (input: 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\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 * @typedef {LngLat | {lng: number, lat: number} | {lon: number, lat: number} | [number, number]} LngLatLike\n * @example\n * var v1 = new mapboxgl.LngLat(-122.420679, 37.772537);\n * var v2 = [-122.420679, 37.772537];\n * var v3 = {lon: -122.420679, lat: 37.772537};\n */\nexport type LngLatLike = LngLat | {lng: number, lat: number} | {lon: number, lat: number} | [number, number];\n\nexport default LngLat;\n","// @flow\n\nimport LngLat from '../geo/lng_lat';\nimport type {LngLatLike} from '../geo/lng_lat';\n\n/*\n * The circumference of the world in meters at the equator.\n */\nconst circumferenceAtEquator = 2 * Math.PI * 6378137;\n\n/*\n * The circumference of the world in meters at the given latitude.\n */\nfunction circumferenceAtLatitude(latitude: number) {\n return circumferenceAtEquator * 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 {number} lat Latitude\n * @returns {number} 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 * - 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 * @param {number} x The x component of the position.\n * @param {number} y The y component of the position.\n * @param {number} z The z component of the position.\n * @example\n * var nullIsland = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);\n *\n * @see [Add a custom style layer](https://www.mapbox.com/mapbox-gl-js/example/custom-style-layer/)\n */\nclass MercatorCoordinate {\n x: number;\n y: number;\n z: number;\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} lngLatLike The location to project.\n * @param {number} altitude The altitude in meters of the position.\n * @returns {MercatorCoordinate} The projected mercator coordinate.\n * @example\n * var coord = mapboxgl.MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0);\n * coord; // MercatorCoordinate(0.5, 0.5, 0)\n */\n static fromLngLat(lngLatLike: LngLatLike, altitude: number = 0) {\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 {LngLat} The `LngLat` object.\n * @example\n * var coord = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);\n * var latLng = coord.toLngLat(); // LngLat(0, 0)\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 {number} The altitude in meters.\n * @example\n * var coord = new mapboxgl.MercatorCoordinate(0, 0, 0.02);\n * coord.toAltitude(); // 6914.281956295339\n */\n toAltitude() {\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 {number} Distance of 1 meter in `MercatorCoordinate` units.\n */\n meterInMercatorCoordinateUnits() {\n // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude\n return 1 / circumferenceAtEquator * mercatorScale(latFromMercatorY(this.y));\n }\n\n}\n\nexport default MercatorCoordinate;\n","// @flow\n\nimport {getTileBBox} from '@mapbox/whoots-js';\nimport EXTENT from '../data/extent';\nimport Point from '@mapbox/point-geometry';\nimport MercatorCoordinate from '../geo/mercator_coordinate';\n\nimport assert from 'assert';\nimport { register } from '../util/web_worker_transfer';\n\nexport class CanonicalTileID {\n z: number;\n x: number;\n y: number;\n key: number;\n\n constructor(z: number, x: number, y: number) {\n assert(z >= 0 && z <= 25);\n assert(x >= 0 && x < Math.pow(2, z));\n assert(y >= 0 && y < Math.pow(2, z));\n this.z = z;\n this.x = x;\n this.y = y;\n this.key = calculateKey(0, z, x, y);\n }\n\n equals(id: CanonicalTileID) {\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, scheme: ?string) {\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}', (this.x % 16).toString(16) + (this.y % 16).toString(16))\n .replace('{z}', String(this.z))\n .replace('{x}', String(this.x))\n .replace('{y}', String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y))\n .replace('{quadkey}', quadkey)\n .replace('{bbox-epsg-3857}', bbox);\n }\n\n getTilePoint(coord: MercatorCoordinate) {\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\nexport class UnwrappedTileID {\n wrap: number;\n canonical: CanonicalTileID;\n key: number;\n\n constructor(wrap: number, canonical: CanonicalTileID) {\n this.wrap = wrap;\n this.canonical = canonical;\n this.key = calculateKey(wrap, canonical.z, canonical.x, canonical.y);\n }\n}\n\nexport class OverscaledTileID {\n overscaledZ: number;\n wrap: number;\n canonical: CanonicalTileID;\n key: number;\n posMatrix: Float32Array;\n\n constructor(overscaledZ: number, wrap: number, z: number, x: number, y: number) {\n assert(overscaledZ >= z);\n this.overscaledZ = overscaledZ;\n this.wrap = wrap;\n this.canonical = new CanonicalTileID(z, +x, +y);\n this.key = calculateKey(wrap, overscaledZ, x, 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 assert(targetZ <= 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 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, z: number, x: number, y: number) {\n wrap *= 2;\n if (wrap < 0) wrap = wrap * -1 - 1;\n const dim = 1 << z;\n return ((dim * dim * wrap + dim * y + x) * 32) + z;\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","// @flow\n\nimport { pick, extend } from '../util/util';\n\nimport { getJSON, ResourceType } from '../util/ajax';\nimport browser from '../util/browser';\n\nimport type {RequestManager} from '../util/mapbox';\nimport type {Callback} from '../types/callback';\nimport type {TileJSON} from '../types/tilejson';\nimport type {Cancelable} from '../types/cancelable';\n\nexport default function(options: any, requestManager: RequestManager, callback: Callback): Cancelable {\n const loaded = function(err: ?Error, tileJSON: ?Object) {\n if (err) {\n return callback(err);\n } else if (tileJSON) {\n const result: any = pick(\n // explicit source options take precedence over TileJSON\n extend(tileJSON, options),\n ['tiles', 'minzoom', 'maxzoom', 'attribution', 'mapbox_logo', 'bounds', 'scheme', 'tileSize', 'encoding']\n );\n\n if (tileJSON.vector_layers) {\n result.vectorLayers = tileJSON.vector_layers;\n result.vectorLayerIds = result.vectorLayers.map((layer) => { return layer.id; });\n }\n\n // only canonicalize tile tileset if source is declared using a tilejson url\n if (options.url) {\n result.tiles = requestManager.canonicalizeTileset(result, options.url);\n }\n callback(null, result);\n }\n };\n\n if (options.url) {\n return getJSON(requestManager.transformRequest(requestManager.normalizeSourceURL(options.url), ResourceType.Source), loaded);\n } else {\n return browser.frame(() => loaded(null, options));\n }\n}\n","// @flow\n\nimport LngLatBounds from '../geo/lng_lat_bounds';\nimport {mercatorXfromLng, mercatorYfromLat} from '../geo/mercator_coordinate';\n\nimport type {CanonicalTileID} from './tile_id';\n\nclass TileBounds {\n bounds: LngLatBounds;\n minzoom: number;\n maxzoom: number;\n\n constructor(bounds: [number, number, number, number], minzoom: ?number, maxzoom: ?number) {\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]) {\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\nexport default TileBounds;\n","// @flow\n\nimport { Event, ErrorEvent, Evented } from '../util/evented';\n\nimport { extend, pick } from '../util/util';\nimport loadTileJSON from './load_tilejson';\nimport { postTurnstileEvent, postMapLoadEvent } from '../util/mapbox';\nimport TileBounds from './tile_bounds';\nimport { ResourceType } from '../util/ajax';\nimport browser from '../util/browser';\nimport { cacheEntryPossiblyAdded } from '../util/tile_request_cache';\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 {Callback} from '../types/callback';\nimport type {Cancelable} from '../types/cancelable';\nimport type {VectorSourceSpecification} from '../style-spec/types';\n\nclass 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\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: ?Cancelable;\n _loaded: boolean;\n\n constructor(id: string, options: VectorSourceSpecification & {collectResourceTiming: boolean}, 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']));\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 load() {\n this._loaded = false;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, (err, tileJSON) => {\n this._tileJSONRequest = null;\n this._loaded = true;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (tileJSON) {\n extend(this, tileJSON);\n if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);\n postTurnstileEvent(tileJSON.tiles, this.map._requestManager._customAccessToken);\n postMapLoadEvent(tileJSON.tiles, this.map._getMapId(), this.map._requestManager._skuToken, this.map._requestManager._customAccessToken);\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 });\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 onRemove() {\n if (this._tileJSONRequest) {\n this._tileJSONRequest.cancel();\n this._tileJSONRequest = null;\n }\n }\n\n serialize() {\n return extend({}, this._options);\n }\n\n loadTile(tile: Tile, callback: Callback) {\n const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.url, null);\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: browser.devicePixelRatio,\n showCollisionBoxes: this.map.showCollisionBoxes,\n };\n params.request.collectResourceTiming = this._collectResourceTiming;\n\n if (!tile.actor || tile.state === 'expired') {\n tile.actor = this.dispatcher.getActor();\n tile.request = tile.actor.send('loadTile', params, done.bind(this));\n } else if (tile.state === 'loading') {\n // schedule tile reloading after it has been loaded\n tile.reloadCallback = callback;\n } else {\n tile.request = tile.actor.send('reloadTile', params, done.bind(this));\n }\n\n function done(err, data) {\n delete tile.request;\n\n if (tile.aborted)\n return callback(null);\n\n if (err && err.status !== 404) {\n return callback(err);\n }\n\n if (data && data.resourceTiming)\n tile.resourceTiming = data.resourceTiming;\n\n if (this.map._refreshExpiredTiles && data) tile.setExpiryData(data);\n tile.loadVectorData(data, this.map.painter);\n\n cacheEntryPossiblyAdded(this.dispatcher);\n\n callback(null);\n\n if (tile.reloadCallback) {\n this.loadTile(tile, tile.reloadCallback);\n tile.reloadCallback = null;\n }\n }\n }\n\n abortTile(tile: Tile) {\n if (tile.request) {\n tile.request.cancel();\n delete tile.request;\n }\n if (tile.actor) {\n tile.actor.send('abortTile', { uid: tile.uid, type: this.type, source: this.id }, undefined);\n }\n }\n\n unloadTile(tile: Tile) {\n tile.unloadVectorData();\n if (tile.actor) {\n tile.actor.send('removeTile', { uid: tile.uid, type: this.type, source: this.id }, undefined);\n }\n }\n\n hasTransition() {\n return false;\n }\n}\n\nexport default VectorTileSource;\n","// @flow\n\nimport { extend, pick } from '../util/util';\n\nimport { getImage, ResourceType } from '../util/ajax';\nimport { Event, ErrorEvent, Evented } from '../util/evented';\nimport loadTileJSON from './load_tilejson';\nimport { postTurnstileEvent, postMapLoadEvent } from '../util/mapbox';\nimport TileBounds from './tile_bounds';\nimport Texture from '../render/texture';\n\nimport { cacheEntryPossiblyAdded } from '../util/tile_request_cache';\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 {Callback} from '../types/callback';\nimport type {Cancelable} from '../types/cancelable';\nimport type {\n RasterSourceSpecification,\n RasterDEMSourceSpecification\n} from '../style-spec/types';\n\nclass 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: ?Cancelable;\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 load() {\n this._loaded = false;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, (err, tileJSON) => {\n this._tileJSONRequest = null;\n this._loaded = true;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (tileJSON) {\n extend(this, tileJSON);\n if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);\n\n postTurnstileEvent(tileJSON.tiles);\n postMapLoadEvent(tileJSON.tiles, this.map._getMapId(), this.map._requestManager._skuToken);\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 });\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.cancel();\n this._tileJSONRequest = null;\n }\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 loadTile(tile: Tile, callback: Callback) {\n const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.url, this.tileSize);\n tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), (err, img) => {\n delete tile.request;\n\n if (tile.aborted) {\n tile.state = 'unloaded';\n callback(null);\n } else if (err) {\n tile.state = 'errored';\n callback(err);\n } else if (img) {\n if (this.map._refreshExpiredTiles) tile.setExpiryData(img);\n delete (img: any).cacheControl;\n delete (img: any).expires;\n\n const context = this.map.painter.context;\n const gl = context.gl;\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 if (context.extTextureFilterAnisotropic) {\n gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);\n }\n }\n\n tile.state = 'loaded';\n\n cacheEntryPossiblyAdded(this.dispatcher);\n\n callback(null);\n }\n });\n }\n\n abortTile(tile: Tile, callback: Callback) {\n if (tile.request) {\n tile.request.cancel();\n delete tile.request;\n }\n callback();\n }\n\n unloadTile(tile: Tile, callback: Callback) {\n if (tile.texture) this.map.painter.saveTileTexture(tile.texture);\n callback();\n }\n\n hasTransition() {\n return false;\n }\n}\n\nexport default RasterTileSource;\n","// @flow\nimport { RGBAImage } from '../util/image';\n\nimport { warnOnce } from '../util/util';\nimport { register } from '../util/web_worker_transfer';\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 serliazed 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 default class DEMData {\n uid: string;\n data: Int32Array;\n stride: number;\n dim: number;\n\n constructor(uid: string, data: RGBAImage, encoding: \"mapbox\" | \"terrarium\") {\n this.uid = uid;\n if (data.height !== data.width) throw new RangeError('DEM tiles must be square');\n if (encoding && encoding !== \"mapbox\" && encoding !== \"terrarium\") return warnOnce(\n `\"${encoding}\" is not a valid encoding type. Valid types include \"mapbox\" and \"terrarium\".`\n );\n const dim = this.dim = data.height;\n this.stride = this.dim + 2;\n this.data = new Int32Array(this.stride * this.stride);\n\n const pixels = data.data;\n const unpack = encoding === \"terrarium\" ? this._unpackTerrarium : this._unpackMapbox;\n for (let y = 0; y < dim; y++) {\n for (let x = 0; x < dim; x++) {\n const i = y * dim + x;\n const j = i * 4;\n this.set(x, y, unpack(pixels[j], pixels[j + 1], pixels[j + 2]));\n }\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.set(-1, x, this.get(0, x));\n // right vertical border\n this.set(dim, x, this.get(dim - 1, x));\n // left horizontal border\n this.set(x, -1, this.get(x, 0));\n // right horizontal border\n this.set(x, dim, this.get(x, dim - 1));\n }\n // corners\n this.set(-1, -1, this.get(0, 0));\n this.set(dim, -1, this.get(dim - 1, 0));\n this.set(-1, dim, this.get(0, dim - 1));\n this.set(dim, dim, this.get(dim - 1, dim - 1));\n }\n\n set(x: number, y: number, value: number) {\n this.data[this._idx(x, y)] = value + 65536;\n }\n\n get(x: number, y: number) {\n return this.data[this._idx(x, y)] - 65536;\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 _unpackMapbox(r: number, g: number, b: number) {\n // unpacking formula for mapbox.terrain-rgb:\n // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb\n return ((r * 256 * 256 + g * 256.0 + b) / 10.0 - 10000.0);\n }\n\n _unpackTerrarium(r: number, g: number, b: number) {\n // unpacking formula for mapzen terrarium:\n // https://aws.amazon.com/public-datasets/terrain/\n return ((r * 256 + g + b / 256) - 32768.0);\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.set(x, y, borderTile.get(x + ox, y + oy));\n }\n }\n }\n}\n\nregister('DEMData', DEMData);\n","// @flow\n\nimport { getImage, ResourceType } from '../util/ajax';\nimport { extend } from '../util/util';\nimport { Evented } from '../util/evented';\nimport browser from '../util/browser';\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';\n\nimport type {Source} from './source';\nimport type Dispatcher from '../util/dispatcher';\nimport type Tile from './tile';\nimport type {Callback} from '../types/callback';\nimport type {RasterDEMSourceSpecification} from '../style-spec/types';\n\nclass RasterDEMTileSource extends RasterTileSource implements Source {\n encoding: \"mapbox\" | \"terrarium\";\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 }\n\n serialize() {\n return {\n type: 'raster-dem',\n url: this.url,\n tileSize: this.tileSize,\n tiles: this.tiles,\n bounds: this.bounds,\n encoding: this.encoding\n };\n }\n\n loadTile(tile: Tile, callback: Callback) {\n const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.url, this.tileSize);\n tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), imageLoaded.bind(this));\n\n tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);\n function imageLoaded(err, img) {\n delete tile.request;\n if (tile.aborted) {\n tile.state = 'unloaded';\n callback(null);\n } else if (err) {\n tile.state = 'errored';\n callback(err);\n } else if (img) {\n if (this.map._refreshExpiredTiles) tile.setExpiryData(img);\n delete (img: any).cacheControl;\n delete (img: any).expires;\n\n const rawImageData = browser.getImageData(img);\n const params = {\n uid: tile.uid,\n coord: tile.tileID,\n source: this.id,\n rawImageData,\n encoding: this.encoding\n };\n\n if (!tile.actor || tile.state === 'expired') {\n tile.actor = this.dispatcher.getActor();\n tile.actor.send('loadDEMTile', params, done.bind(this));\n }\n }\n }\n\n function done(err, dem) {\n if (err) {\n tile.state = 'errored';\n callback(err);\n }\n\n if (dem) {\n tile.dem = dem;\n tile.needsHillshadePrepare = true;\n tile.state = 'loaded';\n callback(null);\n }\n }\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 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 tile.actor.send('removeDEMTile', { uid: tile.uid, source: this.id });\n }\n }\n\n}\n\nexport default RasterDEMTileSource;\n","// @flow\n\nimport { Event, ErrorEvent, Evented } from '../util/evented';\n\nimport { extend } from '../util/util';\nimport EXTENT from '../data/extent';\nimport { ResourceType } from '../util/ajax';\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 {Callback} from '../types/callback';\nimport type {GeoJSON, GeoJSONFeature} from '@mapbox/geojson-types';\nimport type {GeoJSONSourceSpecification} from '../style-spec/types';\n\n/**\n * A source containing GeoJSON.\n * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson) for detailed documentation of options.)\n *\n * @example\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 * @example\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 * @example\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 * @see [Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/)\n * @see [Add a GeoJSON line](https://www.mapbox.com/mapbox-gl-js/example/geojson-line/)\n * @see [Create a heatmap from points](https://www.mapbox.com/mapbox-gl-js/example/heatmap/)\n * @see [Create and style clusters](https://www.mapbox.com/mapbox-gl-js/example/cluster/)\n */\nclass GeoJSONSource extends Evented implements Source {\n type: 'geojson';\n id: string;\n minzoom: number;\n maxzoom: number;\n tileSize: number;\n attribution: string;\n\n isTileClipped: boolean;\n reparseOverscaled: boolean;\n _data: GeoJSON | string;\n _options: any;\n workerOptions: any;\n map: Map;\n actor: Actor;\n _loaded: boolean;\n _collectResourceTiming: boolean;\n _resourceTiming: Array;\n _removed: boolean;\n\n /**\n * @private\n */\n constructor(id: string, options: GeoJSONSourceSpecification & {workerOptions?: any, collectResourceTiming: boolean}, 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._loaded = false;\n\n this.actor = dispatcher.getActor();\n this.setEventedParent(eventedParent);\n\n this._data = (options.data: any);\n this._options = extend({}, options);\n\n this._collectResourceTiming = options.collectResourceTiming;\n this._resourceTiming = [];\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\n const scale = EXTENT / this.tileSize;\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 ?\n Math.min(options.clusterMaxZoom, this.maxzoom - 1) :\n (this.maxzoom - 1),\n extent: EXTENT,\n radius: (options.clusterRadius || 50) * scale,\n log: false\n },\n clusterProperties: options.clusterProperties\n }, options.workerOptions);\n }\n\n load() {\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._updateWorkerData((err) => {\n if (err) {\n this.fire(new ErrorEvent(err));\n return;\n }\n\n const data: Object = { dataType: 'source', sourceDataType: 'metadata' };\n if (this._collectResourceTiming && this._resourceTiming && (this._resourceTiming.length > 0)) {\n data.resourceTiming = this._resourceTiming;\n this._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));\n });\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 {Object|string} data A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.\n * @returns {GeoJSONSource} this\n */\n setData(data: GeoJSON | string) {\n this._data = data;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._updateWorkerData((err) => {\n if (err) {\n this.fire(new ErrorEvent(err));\n return;\n }\n\n const data: Object = { dataType: 'source', sourceDataType: 'content' };\n if (this._collectResourceTiming && this._resourceTiming && (this._resourceTiming.length > 0)) {\n data.resourceTiming = this._resourceTiming;\n this._resourceTiming = [];\n }\n this.fire(new Event('data', data));\n });\n\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 * @param callback A callback to be called when the zoom value is retrieved (`(error, zoom) => { ... }`).\n * @returns {GeoJSONSource} this\n */\n getClusterExpansionZoom(clusterId: number, callback: Callback) {\n this.actor.send('geojson.getClusterExpansionZoom', { clusterId, source: this.id }, callback);\n return this;\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 * @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).\n * @returns {GeoJSONSource} this\n */\n getClusterChildren(clusterId: number, callback: Callback>) {\n this.actor.send('geojson.getClusterChildren', { clusterId, source: this.id }, callback);\n return this;\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 * @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).\n * @returns {GeoJSONSource} this\n */\n getClusterLeaves(clusterId: number, limit: number, offset: number, callback: Callback>) {\n this.actor.send('geojson.getClusterLeaves', {\n source: this.id,\n clusterId,\n limit,\n offset\n }, callback);\n return this;\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 */\n _updateWorkerData(callback: Callback) {\n this._loaded = false;\n const options = extend({}, this.workerOptions);\n const data = this._data;\n if (typeof data === 'string') {\n options.request = this.map._requestManager.transformRequest(browser.resolveURL(data), ResourceType.Source);\n options.request.collectResourceTiming = this._collectResourceTiming;\n } else {\n options.data = JSON.stringify(data);\n }\n\n // target {this.type}.loadData rather than literally geojson.loadData,\n // so that other geojson-like source types can easily reuse this\n // implementation\n this.actor.send(`${this.type}.loadData`, options, (err, result) => {\n if (this._removed || (result && result.abandoned)) {\n return;\n }\n\n this._loaded = true;\n\n if (result && result.resourceTiming && result.resourceTiming[this.id])\n this._resourceTiming = result.resourceTiming[this.id].slice(0);\n // Any `loadData` calls that piled up while we were processing\n // this one will get coalesced into a single call when this\n // 'coalesce' message is processed.\n // We would self-send from the worker if we had access to its\n // message queue. Waiting instead for the 'coalesce' to round-trip\n // through the foreground just means we're throttling the worker\n // to run at a little less than full-throttle.\n this.actor.send(`${this.type}.coalesce`, { source: options.source }, null);\n callback(err);\n });\n }\n\n loaded(): boolean {\n return this._loaded;\n }\n\n loadTile(tile: Tile, callback: Callback) {\n const message = !tile.actor ? 'loadTile' : '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: browser.devicePixelRatio,\n showCollisionBoxes: this.map.showCollisionBoxes\n };\n\n tile.request = this.actor.send(message, params, (err, data) => {\n delete tile.request;\n tile.unloadVectorData();\n\n if (tile.aborted) {\n return callback(null);\n }\n\n if (err) {\n return callback(err);\n }\n\n tile.loadVectorData(data, this.map.painter, message === 'reloadTile');\n\n return callback(null);\n });\n }\n\n abortTile(tile: Tile) {\n if (tile.request) {\n tile.request.cancel();\n delete tile.request;\n }\n tile.aborted = true;\n }\n\n unloadTile(tile: Tile) {\n tile.unloadVectorData();\n this.actor.send('removeTile', { uid: tile.uid, type: this.type, source: this.id });\n }\n\n onRemove() {\n this._removed = true;\n this.actor.send('removeSource', { type: this.type, source: this.id });\n }\n\n serialize() {\n return extend({}, this._options, {\n type: this.type,\n data: this._data\n });\n }\n\n hasTransition() {\n return false;\n }\n}\n\nexport default GeoJSONSource;\n","// @flow\n\nimport { CanonicalTileID } from './tile_id';\nimport { Event, ErrorEvent, Evented } from '../util/evented';\nimport { getImage, ResourceType } from '../util/ajax';\nimport EXTENT from '../data/extent';\nimport { RasterBoundsArray } from '../data/array_types';\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 {Callback} from '../types/callback';\nimport type VertexBuffer from '../gl/vertex_buffer';\nimport type {\n ImageSourceSpecification,\n VideoSourceSpecification\n} from '../style-spec/types';\n\ntype Coordinates = [[number, number], [number, number], [number, number], [number, number]];\n\n/**\n * A data source containing an image.\n * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-image) for detailed documentation of options.)\n *\n * @example\n * // add to map\n * map.addSource('some id', {\n * type: 'image',\n * url: 'https://www.mapbox.com/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 * var 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.mapbox.com/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 * @see [Add an image](https://www.mapbox.com/mapbox-gl-js/example/image-on-a-map/)\n */\nclass 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;\n tileID: CanonicalTileID;\n _boundsArray: RasterBoundsArray;\n boundsBuffer: VertexBuffer;\n boundsSegments: SegmentVector;\n _loaded: boolean;\n\n /**\n * @private\n */\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 load(newCoordinates?: Coordinates, successCallback?: () => void) {\n this._loaded = false;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n\n this.url = this.options.url;\n\n getImage(this.map._requestManager.transformRequest(this.url, ResourceType.Image), (err, image) => {\n this._loaded = true;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (image) {\n this.image = image;\n if (newCoordinates) {\n this.coordinates = newCoordinates;\n }\n if (successCallback) {\n successCallback();\n }\n this._finishLoading();\n }\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 {Object} options\n * @param {string} [options.url] Required image URL.\n * @param {Array>} [options.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 * @returns {ImageSource} this\n */\n updateImage(options: {url: string, coordinates?: Coordinates}) {\n if (!this.image || !options.url) {\n return this;\n }\n this.options.url = options.url;\n this.load(options.coordinates, () => { 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 /**\n * Sets the image's coordinates and re-renders the map.\n *\n * @param {Array>} 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 * @returns {ImageSource} this\n */\n setCoordinates(coordinates: Coordinates) {\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 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 }\n }\n }\n\n loadTile(tile: Tile, callback: Callback) {\n // We have a single tile -- whoose 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 callback(null);\n } else {\n tile.state = 'errored';\n callback(null);\n }\n }\n\n serialize(): Object {\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 * @private\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\nexport default ImageSource;\n","// @flow\n\nimport { getVideo, ResourceType } from '../util/ajax';\n\nimport ImageSource from './image_source';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport SegmentVector from '../data/segment';\nimport Texture from '../render/texture';\nimport { ErrorEvent } from '../util/evented';\nimport ValidationError from '../style-spec/error/validation_error';\n\nimport type Map from '../ui/map';\nimport type Dispatcher from '../util/dispatcher';\nimport type {Evented} from '../util/evented';\nimport type {VideoSourceSpecification} from '../style-spec/types';\n\n/**\n * A data source containing video.\n * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-video) for detailed documentation of options.)\n *\n * @example\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 * var 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 * @see [Add a video](https://www.mapbox.com/mapbox-gl-js/example/video-on-a-map/)\n */\nclass VideoSource extends ImageSource {\n options: VideoSourceSpecification;\n urls: Array;\n video: HTMLVideoElement;\n roundZoom: boolean;\n\n /**\n * @private\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 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\n getVideo(this.urls, (err, video) => {\n this._loaded = true;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (video) {\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 }\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(`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 {HTMLVideoElement} The HTML `video` element.\n */\n getVideo() {\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 * @method setCoordinates\n * @instance\n * @memberof VideoSource\n * @param {Array>} coordinates Four geographical coordinates,\n * represented as arrays of longitude and latitude numbers, which define the corners of the video.\n * The coordinates start at the top left corner of the video and proceed in clockwise order.\n * They do not have to represent a rectangle.\n * @returns {VideoSource} this\n */\n // setCoordinates inherited from ImageSource\n\n prepare() {\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 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 }\n }\n }\n\n serialize() {\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\nexport default VideoSource;\n","// @flow\n\nimport ImageSource from './image_source';\n\nimport window from '../util/window';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport SegmentVector from '../data/segment';\nimport Texture from '../render/texture';\nimport { ErrorEvent } from '../util/evented';\nimport ValidationError from '../style-spec/error/validation_error';\n\nimport type Map from '../ui/map';\nimport type Dispatcher from '../util/dispatcher';\nimport type {Evented} from '../util/evented';\n\nexport type CanvasSourceSpecification = {|\n \"type\": \"canvas\",\n \"coordinates\": [[number, number], [number, number], [number, number], [number, number]],\n \"animate\"?: boolean,\n \"canvas\": string | HTMLCanvasElement\n|};\n\n/**\n * Options to add a canvas source type to the map.\n *\n * @typedef {Object} CanvasSourceOptions\n * @property {string} type Source type. Must be `\"canvas\"`.\n * @property {string|HTMLCanvasElement} canvas Canvas source from which to read pixels. Can be a string representing the ID of the canvas element, or the `HTMLCanvasElement` itself.\n * @property {Array>} coordinates Four geographical coordinates denoting where to place the corners of the canvas, specified in `[longitude, latitude]` pairs.\n * @property {boolean} [animate=true] 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 */\n\n/**\n * A data source containing the contents of an HTML canvas. See {@link CanvasSourceOptions} for detailed documentation of options.\n *\n * @example\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 * var 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 */\nclass CanvasSource extends ImageSource {\n options: CanvasSourceSpecification;\n animate: boolean;\n canvas: HTMLCanvasElement;\n width: number;\n height: number;\n play: () => void;\n pause: () => void;\n _playing: boolean;\n\n /**\n * @private\n */\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 window.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 /**\n * Enables animation. The image will be copied from the canvas to the map on each frame.\n * @method play\n * @instance\n * @memberof CanvasSource\n */\n\n /**\n * Disables animation. The map will display a static copy of the canvas image.\n * @method pause\n * @instance\n * @memberof CanvasSource\n */\n\n load() {\n this._loaded = true;\n if (!this.canvas) {\n this.canvas = (this.options.canvas instanceof window.HTMLCanvasElement) ?\n this.options.canvas :\n window.document.getElementById(this.options.canvas);\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 {HTMLCanvasElement} The HTML `canvas` element.\n */\n getCanvas() {\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 /**\n * Sets the canvas's coordinates and re-renders the map.\n *\n * @method setCoordinates\n * @instance\n * @memberof CanvasSource\n * @param {Array>} coordinates Four geographical coordinates,\n * represented as arrays of longitude and latitude numbers, which define the corners of the canvas.\n * The coordinates start at the top left corner of the canvas and proceed in clockwise order.\n * They do not have to represent a rectangle.\n * @returns {CanvasSource} this\n */\n // setCoordinates inherited from ImageSource\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 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 }\n }\n }\n\n serialize(): Object {\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\nexport default CanvasSource;\n","// @flow\n\nimport { bindAll } from '../util/util';\n\nimport type Dispatcher from '../util/dispatcher';\nimport type {Event, Evented} from '../util/evented';\nimport type Map from '../ui/map';\nimport type Tile from './tile';\nimport type {OverscaledTileID} from './tile_id';\nimport type {Callback} from '../types/callback';\nimport {CanonicalTileID} from './tile_id';\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 * @private\n *\n * @param {string} id The id for the source. Must not be used by any existing source.\n * @param {Object} options Source options, specific to the source type (except for `options.type`, which is always\n * required).\n * @param {string} options.type The source type, matching the value of `name` used in {@link Style#addSourceType}.\n * @param {Dispatcher} dispatcher A {@link Dispatcher} instance, which can be used to send messages to the workers.\n *\n * @fires data 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 * @property {string} id The id for the source. Must match the id passed to the constructor.\n * @property {number} minzoom\n * @property {number} maxzoom\n * @property {boolean} isTileClipped `false` if tiles can be drawn outside their boundaries, `true` if they cannot.\n * @property {boolean} reparseOverscaled `true` if tiles should be sent back to the worker for each overzoomed zoom\n * level, `false` if not.\n * @property {boolean} roundZoom `true` if zoom levels are rounded to the nearest integer in the source data, `false`\n * if they are floor-ed to the nearest integer.\n */\nexport interface Source {\n +type: string;\n id: string;\n minzoom: number,\n maxzoom: number,\n tileSize: number,\n attribution?: string,\n\n roundZoom?: boolean,\n isTileClipped?: boolean,\n mapbox_logo?: boolean,\n tileID?: CanonicalTileID;\n reparseOverscaled?: boolean,\n vectorLayerIds?: Array,\n\n hasTransition(): boolean;\n loaded(): boolean;\n\n fire(event: Event): mixed;\n\n +onAdd?: (map: Map) => void;\n +onRemove?: (map: Map) => void;\n\n loadTile(tile: Tile, callback: Callback): void;\n +hasTile?: (tileID: OverscaledTileID) => boolean;\n +abortTile?: (tile: Tile, callback: Callback) => void;\n +unloadTile?: (tile: Tile, callback: Callback) => void;\n\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 * @private\n */\n serialize(): Object;\n\n +prepare?: () => void;\n}\n\ntype SourceStatics = {\n /*\n * An optional URL to a script which, when run by a Worker, registers a {@link WorkerSource}\n * implementation for this Source type by calling `self.registerWorkerSource(workerSource: WorkerSource)`.\n */\n workerSourceURL?: URL;\n};\n\nexport type SourceClass = Class & SourceStatics;\n\nimport vector from '../source/vector_tile_source';\nimport raster from '../source/raster_tile_source';\nimport rasterDem from '../source/raster_dem_tile_source';\nimport geojson from '../source/geojson_source';\nimport video from '../source/video_source';\nimport image from '../source/image_source';\nimport canvas from '../source/canvas_source';\n\nimport type {SourceSpecification} from '../style-spec/types';\n\nconst sourceTypes = {\n vector,\n raster,\n 'raster-dem': rasterDem,\n geojson,\n video,\n image,\n canvas\n};\n\n/*\n * Creates a tiled data source instance given an options object.\n *\n * @param id\n * @param {Object} source A source definition object compliant with\n * [`mapbox-gl-style-spec`](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or, for a third-party source type,\n * with that type's requirements.\n * @param {Dispatcher} dispatcher\n * @returns {Source}\n */\nexport const create = function(id: string, specification: SourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n const source = new sourceTypes[specification.type](id, (specification: any), 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 bindAll(['load', 'abort', 'unload', 'serialize', 'prepare'], source);\n return source;\n};\n\nexport const getType = function (name: string) {\n return sourceTypes[name];\n};\n\nexport const setType = function (name: string, type: Class) {\n sourceTypes[name] = type;\n};\n\nexport interface Actor {\n send(type: string, data: Object, callback: Callback): void;\n}\n","// @flow\n\nimport 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 '../style-spec/types';\nimport assert from 'assert';\nimport { mat4 } from 'gl-matrix';\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.identity([]);\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(sourceCache: SourceCache,\n styleLayers: {[string]: StyleLayer},\n queryGeometry: Array,\n params: { filter: FilterSpecification, layers: Array },\n transform: Transform) {\n\n const has3DLayer = queryIncludes3DLayer(params && params.layers, styleLayers, sourceCache.id);\n\n const maxPitchScaleFactor = transform.maxPitchScaleFactor();\n const tilesIn = sourceCache.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer);\n\n tilesIn.sort(sortTilesIn);\n\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 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;\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 sourceCaches: {[string]: SourceCache},\n queryGeometry: Array,\n params: { filter: FilterSpecification, layers: Array },\n collisionIndex: CollisionIndex,\n retainedQueryData: {[number]: RetainedQueryData}) {\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 queryData.bucketIndex,\n queryData.sourceLayerIndex,\n params.filter,\n params.layers,\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 assert(sortedA >= 0);\n assert(sortedB >= 0);\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: any) {\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","// @flow strict\n\nimport assert from 'assert';\n\nclass 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 assert(string in this._stringToNumber);\n return this._stringToNumber[string];\n }\n\n decode(n: number) {\n assert(n < this._numberToString.length);\n return this._numberToString[n];\n }\n}\n\nexport default DictionaryCoder;\n","// @flow\nimport type {GeoJSONGeometry} from '@mapbox/geojson-types';\n\nclass Feature {\n type: 'Feature';\n _geometry: ?GeoJSONGeometry;\n properties: {};\n id: number | string | void;\n\n _vectorTileFeature: VectorTileFeature;\n\n constructor(vectorTileFeature: VectorTileFeature, z: number, x: number, y: number) {\n this.type = 'Feature';\n\n this._vectorTileFeature = vectorTileFeature;\n (vectorTileFeature: any)._z = z;\n (vectorTileFeature: any)._x = x;\n (vectorTileFeature: any)._y = y;\n\n this.properties = vectorTileFeature.properties;\n\n if (vectorTileFeature.id != null) {\n this.id = vectorTileFeature.id;\n }\n }\n\n get geometry(): ?GeoJSONGeometry {\n if (this._geometry === undefined) {\n this._geometry = this._vectorTileFeature.toGeoJSON(\n (this._vectorTileFeature: any)._x,\n (this._vectorTileFeature: any)._y,\n (this._vectorTileFeature: any)._z).geometry;\n }\n return this._geometry;\n }\n\n set geometry(g: ?GeoJSONGeometry) {\n this._geometry = g;\n }\n\n toJSON() {\n const json = {\n geometry: this.geometry\n };\n for (const i in this) {\n if (i === '_geometry' || i === '_vectorTileFeature') continue;\n json[i] = (this: any)[i];\n }\n return json;\n }\n}\n\nexport default Feature;\n","// @flow\n\nimport { extend } from '../util/util';\nimport Tile from './tile';\nimport type {FeatureState} from '../style-spec/expression';\n\nexport type FeatureStates = {[feature_id: string]: FeatureState};\nexport type LayerFeatureStates = {[layer: string]: FeatureStates};\n\n/**\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 * @private\n*/\nclass 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, newState: Object) {\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, 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 && featureId >= 0) {\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 && featureId >= 0) {\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) {\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: {[any]: Tile}, 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\nexport default SourceFeatureState;\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport loadGeometry from './load_geometry';\nimport EXTENT from './extent';\nimport featureFilter from '../style-spec/feature_filter';\nimport Grid from '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 { arraysIntersect } 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';\n\nimport type StyleLayer from '../style/style_layer';\nimport type {FeatureFilter} from '../style-spec/feature_filter';\nimport type Transform from '../geo/transform';\nimport type {FilterSpecification} from '../style-spec/types';\n\nimport { FeatureIndexArray } from './array_types';\n\ntype QueryParameters = {\n scale: number,\n pixelPosMatrix: Float32Array,\n transform: Transform,\n tileSize: number,\n queryGeometry: Array,\n cameraQueryGeometry: Array,\n queryPadding: number,\n params: {\n filter: FilterSpecification,\n layers: Array,\n }\n}\n\nclass FeatureIndex {\n tileID: OverscaledTileID;\n x: number;\n y: number;\n z: number;\n grid: Grid;\n grid3D: Grid;\n featureIndexArray: FeatureIndexArray;\n\n rawTileData: ArrayBuffer;\n bucketLayerIDs: Array>;\n\n vtLayers: {[string]: VectorTileLayer};\n sourceLayerCoder: DictionaryCoder;\n\n constructor(tileID: OverscaledTileID,\n grid?: Grid,\n featureIndexArray?: FeatureIndexArray) {\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 = grid || new Grid(EXTENT, 16, 0);\n this.grid3D = new Grid(EXTENT, 16, 0);\n this.featureIndexArray = featureIndexArray || new FeatureIndexArray();\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(args: QueryParameters, styleLayers: {[string]: StyleLayer}, sourceFeatureState: SourceFeatureState): {[string]: Array<{ featureIndex: number, feature: GeoJSONFeature }>} {\n this.loadVTLayers();\n\n const params = args.params || {},\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 styleLayers,\n (feature: VectorTileFeature, styleLayer: StyleLayer) => {\n if (!featureGeometry) {\n featureGeometry = loadGeometry(feature);\n }\n let featureState = {};\n if (feature.id) {\n // `feature-state` expression evaluation requires feature state to be available\n featureState = sourceFeatureState.getState(styleLayer.sourceLayer || '_geojsonTileLayer', feature.id);\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: {[string]: Array<{ featureIndex: number, feature: GeoJSONFeature }>},\n bucketIndex: number,\n sourceLayerIndex: number,\n featureIndex: number,\n filter: FeatureFilter,\n filterLayerIDs: Array,\n styleLayers: {[string]: StyleLayer},\n intersectionTest?: (feature: VectorTileFeature, styleLayer: StyleLayer) => 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(new EvaluationParameters(this.tileID.overscaledZ), feature))\n return;\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 if (!styleLayer) continue;\n\n const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer);\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);\n (geojsonFeature: any).layer = styleLayer.serialize();\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 bucketIndex: number,\n sourceLayerIndex: number,\n filterSpec: FilterSpecification,\n filterLayerIDs: 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 styleLayers\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\nregister(\n 'FeatureIndex',\n FeatureIndex,\n { omit: ['rawTileData', 'sourceLayerCoder'] }\n);\n\nexport default FeatureIndex;\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","// @flow\n\nimport { uniqueId, deepEqual, parseCacheControl } from '../util/util';\nimport { deserialize as deserializeBucket } from '../data/bucket';\nimport FeatureIndex from '../data/feature_index';\nimport GeoJSONFeature from '../util/vectortile_to_geojson';\nimport featureFilter from '../style-spec/feature_filter';\nimport SymbolBucket from '../data/bucket/symbol_bucket';\nimport { RasterBoundsArray, CollisionBoxArray } from '../data/array_types';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport EXTENT from '../data/extent';\nimport Point from '@mapbox/point-geometry';\nimport Texture from '../render/texture';\nimport SegmentVector from '../data/segment';\nimport { TriangleIndexArray } from '../data/index_array_type';\nimport browser from '../util/browser';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport SourceFeatureState from '../source/source_state';\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 {Mask} from '../render/tile_mask';\nimport type Context from '../gl/context';\nimport type IndexBuffer from '../gl/index_buffer';\nimport type VertexBuffer from '../gl/vertex_buffer';\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 {Cancelable} from '../types/cancelable';\nimport type {FilterSpecification} from '../style-spec/types';\n\nexport type TileState =\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\n * HTTP headers and is in the process of refreshing. */\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 *\n * @private\n */\nclass 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: any;\n fadeEndTime: any;\n collisionBoxArray: ?CollisionBoxArray;\n redoWhenDone: boolean;\n showCollisionBoxes: boolean;\n placementSource: any;\n actor: ?Actor;\n vtLayers: {[string]: VectorTileLayer};\n mask: Mask;\n\n neighboringTiles: ?Object;\n dem: ?DEMData;\n aborted: ?boolean;\n maskedBoundsBuffer: ?VertexBuffer;\n maskedIndexBuffer: ?IndexBuffer;\n segments: ?SegmentVector;\n needsHillshadePrepare: ?boolean;\n request: ?Cancelable;\n texture: any;\n fbo: ?Framebuffer;\n demTexture: ?Texture;\n refreshedUponExpiration: boolean;\n reloadCallback: any;\n resourceTiming: ?Array;\n queryPadding: number;\n\n symbolFadeHoldUntil: ?number;\n hasSymbolBuckets: boolean;\n\n /**\n * @param {OverscaledTileID} tileID\n * @param 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\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 if (fadeEndTime < browser.now()) return;\n if (this.fadeEndTime && fadeEndTime < this.fadeEndTime) return;\n\n this.fadeEndTime = fadeEndTime;\n }\n\n wasRequested() {\n return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading';\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 {Object} data\n * @param painter\n * @returns {undefined}\n * @private\n */\n loadVectorData(data: WorkerTileResult, painter: any, justReloaded: ?boolean) {\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.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 * @returns {undefined}\n * @private\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 unloadDEMData() {\n this.dem = null;\n this.neighboringTiles = 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(layers: {[string]: StyleLayer},\n sourceFeatureState: SourceFeatureState,\n queryGeometry: Array,\n cameraQueryGeometry: Array,\n scale: number,\n params: { filter: FilterSpecification, layers: Array },\n transform: Transform,\n maxPitchScaleFactor: number,\n pixelPosMatrix: Float32Array): {[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, sourceFeatureState);\n }\n\n querySourceFeatures(result: Array, params: any) {\n if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData) return;\n\n const vtLayers = this.latestFeatureIndex.loadVTLayers();\n\n const sourceLayer = params ? 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(new EvaluationParameters(this.tileID.overscaledZ), feature)) {\n const geojsonFeature = new GeoJSONFeature(feature, z, x, y);\n (geojsonFeature: any).tile = coord;\n result.push(geojsonFeature);\n }\n }\n }\n\n clearMask() {\n if (this.segments) {\n this.segments.destroy();\n delete this.segments;\n }\n if (this.maskedBoundsBuffer) {\n this.maskedBoundsBuffer.destroy();\n delete this.maskedBoundsBuffer;\n }\n if (this.maskedIndexBuffer) {\n this.maskedIndexBuffer.destroy();\n delete this.maskedIndexBuffer;\n }\n }\n\n setMask(mask: Mask, context: Context) {\n\n // don't redo buffer work if the mask is the same;\n if (deepEqual(this.mask, mask)) return;\n\n this.mask = mask;\n this.clearMask();\n\n // We want to render the full tile, and keeping the segments/vertices/indices empty means\n // using the global shared buffers for covering the entire tile.\n if (deepEqual(mask, {'0': true})) return;\n\n const maskedBoundsArray = new RasterBoundsArray();\n const indexArray = new TriangleIndexArray();\n\n this.segments = new SegmentVector();\n // Create a new segment so that we will upload (empty) buffers even when there is nothing to\n // draw for this tile.\n this.segments.prepareSegment(0, maskedBoundsArray, indexArray);\n\n const maskArray = Object.keys(mask);\n for (let i = 0; i < maskArray.length; i++) {\n const maskCoord = mask[+maskArray[i]];\n const vertexExtent = EXTENT >> maskCoord.z;\n const tlVertex = new Point(maskCoord.x * vertexExtent, maskCoord.y * vertexExtent);\n const brVertex = new Point(tlVertex.x + vertexExtent, tlVertex.y + vertexExtent);\n\n // not sure why flow is complaining here because it doesn't complain at L401\n const segment = (this.segments: any).prepareSegment(4, maskedBoundsArray, indexArray);\n\n maskedBoundsArray.emplaceBack(tlVertex.x, tlVertex.y, tlVertex.x, tlVertex.y);\n maskedBoundsArray.emplaceBack(brVertex.x, tlVertex.y, brVertex.x, tlVertex.y);\n maskedBoundsArray.emplaceBack(tlVertex.x, brVertex.y, tlVertex.x, brVertex.y);\n maskedBoundsArray.emplaceBack(brVertex.x, brVertex.y, brVertex.x, brVertex.y);\n\n const offset = segment.vertexLength;\n // 0, 1, 2\n // 1, 2, 3\n indexArray.emplaceBack(offset, offset + 1, offset + 2);\n indexArray.emplaceBack(offset + 1, offset + 2, offset + 3);\n\n segment.vertexLength += 4;\n segment.primitiveLength += 2;\n }\n\n this.maskedBoundsBuffer = context.createVertexBuffer(maskedBoundsArray, rasterBoundsAttributes.members);\n this.maskedIndexBuffer = context.createIndexBuffer(indexArray);\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: any) {\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 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 if (painter && painter.style) {\n this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).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\nexport default Tile;\n","// @flow\n\nimport type {CollisionBoxArray} from './array_types';\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';\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}\n\nexport type IndexedFeature = {\n feature: VectorTileFeature,\n index: number,\n sourceLayerIndex: number,\n}\n\nexport type BucketFeature = {|\n index: number,\n sourceLayerIndex: number,\n geometry: Array>,\n properties: Object,\n type: 1 | 2 | 3,\n id?: any,\n +patterns: {[string]: {\"min\": string, \"mid\": string, \"max\": string}},\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:\n * ArrayGroup`. When a bucket's data is serialized and sent back to the main\n * thread, 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 *\n * @private\n */\nexport interface Bucket {\n layerIds: Array;\n hasPattern: boolean;\n +layers: Array;\n +stateDependentLayers: Array;\n +stateDependentLayerIds: Array;\n populate(features: Array, options: PopulateParameters): void;\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[string]: ImagePosition}): void;\n isEmpty(): boolean;\n\n upload(context: Context): void;\n uploadPending(): boolean;\n\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 * @private\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: any).layers = layers;\n if ((bucket: any).stateDependentLayerIds) {\n (bucket: any).stateDependentLayers = (bucket: any).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","// @flow\n\nimport { OverscaledTileID } from './tile_id';\nimport type Tile from './tile';\n\n/**\n * A [least-recently-used cache](http://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 *\n * @private\n */\nclass TileCache {\n max: number;\n data: {[key: number | string]: Array<{ value: Tile, timeout: ?TimeoutID}>};\n order: Array;\n onRemove: (element: Tile) => void;\n /**\n * @param {number} max number of permitted values\n * @param {Function} 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 {TileCache} this cache\n * @private\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 {OverscaledTileID} tileID lookup key for the item\n * @param {*} data any value\n *\n * @returns {TileCache} this cache\n * @private\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);\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 {OverscaledTileID} tileID the key to be looked-up\n * @returns {boolean} whether the cache has this value\n * @private\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 {OverscaledTileID} tileID the key to look up\n * @returns {*} the data, or null if it isn't found\n * @private\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: number): ?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 attached to a specific key without removing data\n * from the cache. If the key is not found, returns `null`\n *\n * @param {OverscaledTileID} tileID the key to look up\n * @returns {*} the data, or null if it isn't found\n * @private\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 {OverscaledTileID} tileID the key for the pair to delete\n * @param {Tile} value If a value is provided, remove that exact version of the value.\n * @returns {TileCache} this cache\n * @private\n */\n remove(tileID: OverscaledTileID, value: ?{ value: Tile, timeout: ?TimeoutID}) {\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 {number} max the max size of the cache\n * @returns {TileCache} this cache\n * @private\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\nexport default TileCache;\n","// @flow\nimport assert from 'assert';\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\nclass 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 assert(this.dynamicDraw);\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\nexport default IndexBuffer;\n","// @flow\n\nimport assert from 'assert';\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 * @enum {string} AttributeType\n * @private\n * @readonly\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 * The `VertexBuffer` class turns a `StructArray` into a WebGL buffer. Each member of the StructArray's\n * Struct type is converted to a WebGL atribute.\n * @private\n */\nclass 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 assert(array.length === 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, 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, program: Program<*>, vertexOffset: ?number) {\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: 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\nexport default VertexBuffer;\n","// @flow\n\nimport Color from '../style-spec/util/color';\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 Value {\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 Value {\n gl: WebGLRenderingContext;\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; // overriden 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 Program extends BaseValue {\n getDefault(): WebGLProgram {\n return null;\n }\n set(v: ?WebGLProgram) {\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) {\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) {\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) {\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) {\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) {\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 BindVertexArrayOES extends BaseValue {\n vao: any;\n\n constructor(context: Context) {\n super(context);\n this.vao = context.extVertexArrayObject;\n }\n getDefault(): any {\n return null;\n }\n set(v: any) {\n if (!this.vao || v === this.current && !this.dirty) return;\n this.vao.bindVertexArrayOES(v);\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: 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: 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): 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 this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthAttachment extends FramebufferAttachment {\n set(v: ?WebGLRenderbuffer): 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","// @flow\nimport { ColorAttachment, DepthAttachment } from './value';\n\nimport type Context from './context';\n\nclass 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) {\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 this.depthAttachment = new DepthAttachment(context, fbo);\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 const renderbuffer = this.depthAttachment.get();\n if (renderbuffer) gl.deleteRenderbuffer(renderbuffer);\n\n gl.deleteFramebuffer(this.framebuffer);\n }\n}\n\nexport default Framebuffer;\n","// @flow\nimport type { DepthFuncType, DepthMaskType, DepthRangeType } from './types';\n\nconst ALWAYS = 0x0207;\n\nclass 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\nexport default DepthMode;\n","// @flow\nimport type { StencilOpConstant, StencilTest } from './types';\n\nconst ALWAYS = 0x0207;\nconst KEEP = 0x1E00;\n\nclass StencilMode {\n test: StencilTest;\n ref: number;\n mask: number;\n fail: StencilOpConstant;\n depthFail: StencilOpConstant;\n pass: StencilOpConstant;\n\n constructor(test: StencilTest, 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\nexport default StencilMode;\n","// @flow\nimport Color from '../style-spec/util/color';\n\nimport type {BlendFuncType, ColorMaskType} from './types';\n\nconst ZERO = 0x0000;\nconst ONE = 0x0001;\nconst ONE_MINUS_SRC_ALPHA = 0x0303;\n\nclass 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\nexport default ColorMode;\n","// @flow\n\nimport type {CullFaceModeType, FrontFaceType} from './types';\n\nconst BACK = 0x0405;\nconst CCW = 0x0901;\n\nclass 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\nexport default CullFaceMode;\n","// @flow\nimport 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, Program, ActiveTextureUnit, Viewport, BindFramebuffer, BindRenderbuffer, BindTexture, BindVertexBuffer, BindElementBuffer, BindVertexArrayOES, 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 '../style-spec/util/color';\n\ntype ClearArgs = {\n color?: Color,\n depth?: number,\n stencil?: number\n};\n\nclass Context {\n gl: WebGLRenderingContext;\n extVertexArrayObject: any;\n currentNumAttributes: ?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: Program;\n activeTexture: ActiveTextureUnit;\n viewport: Viewport;\n bindFramebuffer: BindFramebuffer;\n bindRenderbuffer: BindRenderbuffer;\n bindTexture: BindTexture;\n bindVertexBuffer: BindVertexBuffer;\n bindElementBuffer: BindElementBuffer;\n bindVertexArrayOES: BindVertexArrayOES;\n pixelStoreUnpack: PixelStoreUnpack;\n pixelStoreUnpackPremultiplyAlpha: PixelStoreUnpackPremultiplyAlpha;\n pixelStoreUnpackFlipY: PixelStoreUnpackFlipY;\n\n extTextureFilterAnisotropic: any;\n extTextureFilterAnisotropicMax: any;\n extTextureHalfFloat: any;\n\n constructor(gl: WebGLRenderingContext) {\n this.gl = gl;\n this.extVertexArrayObject = this.gl.getExtension('OES_vertex_array_object');\n\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 Program(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.bindVertexArrayOES = this.extVertexArrayObject && new BindVertexArrayOES(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 if (this.extTextureFilterAnisotropic) {\n this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);\n }\n\n this.extTextureHalfFloat = gl.getExtension('OES_texture_half_float');\n if (this.extTextureHalfFloat) {\n gl.getExtension('OES_texture_half_float_linear');\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 if (this.extVertexArrayObject) {\n this.bindVertexArrayOES.dirty = true;\n }\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) {\n return new Framebuffer(this, width, height);\n }\n\n clear({color, depth}: 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 reseting 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 // See note in Painter#clearStencil: implement this the easy way once GPU bug/workaround is fixed upstream\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 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 if (this.extVertexArrayObject) {\n this.bindVertexArrayOES.set(null);\n }\n }\n}\n\nexport default Context;\n","// @flow\n\nimport { 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 assert from 'assert';\nimport SourceFeatureState from './source_state';\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 {Callback} from '../types/callback';\nimport type {SourceSpecification} from '../style-spec/types';\n\n/**\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 *\n * @private\n */\nclass SourceCache extends Evented {\n id: string;\n dispatcher: Dispatcher;\n map: Map;\n style: Style;\n\n _source: Source;\n _sourceLoaded: boolean;\n _sourceErrored: boolean;\n _tiles: {[any]: Tile};\n _prevLng: number | void;\n _cache: TileCache;\n _timers: {[any]: TimeoutID};\n _cacheTimers: {[any]: TimeoutID};\n _maxTileCacheSize: ?number;\n _paused: boolean;\n _shouldReloadOnResume: boolean;\n _coveredTiles: {[any]: boolean};\n transform: Transform;\n _isIdRenderable: (id: number, symbolLayer?: boolean) => boolean;\n used: boolean;\n _state: SourceFeatureState;\n\n static maxUnderzooming: number;\n static maxOverzooming: number;\n\n constructor(id: string, options: SourceSpecification, dispatcher: Dispatcher) {\n super();\n this.id = id;\n this.dispatcher = dispatcher;\n\n this.on('data', (e) => {\n // this._sourceLoaded 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 if (e.dataType === 'source' && e.sourceDataType === 'metadata') this._sourceLoaded = true;\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\" && e.sourceDataType === 'content') {\n this.reload();\n if (this.transform) {\n this.update(this.transform);\n }\n }\n });\n\n this.on('error', () => {\n this._sourceErrored = true;\n });\n\n this._source = createSource(id, options, dispatcher, this);\n\n this._tiles = {};\n this._cache = new TileCache(0, this._unloadTile.bind(this));\n this._timers = {};\n this._cacheTimers = {};\n this._maxTileCacheSize = null;\n\n this._coveredTiles = {};\n this._state = new SourceFeatureState();\n }\n\n onAdd(map: Map) {\n this.map = map;\n this._maxTileCacheSize = map ? map._maxTileCacheSize : null;\n if (this._source && this._source.onAdd) {\n this._source.onAdd(map);\n }\n }\n\n onRemove(map: Map) {\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 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);\n }\n\n _loadTile(tile: Tile, callback: Callback) {\n return this._source.loadTile(tile, callback);\n }\n\n _unloadTile(tile: Tile) {\n if (this._source.unloadTile)\n return this._source.unloadTile(tile, () => {});\n }\n\n _abortTile(tile: Tile) {\n if (this._source.abortTile)\n return this._source.abortTile(tile, () => {});\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.keys(this._tiles).map(Number).sort(compareKeyZoom);\n }\n\n getRenderableIds(symbolLayer?: boolean): Array {\n const ids = [];\n for (const id in this._tiles) {\n if (this._isIdRenderable(+id, symbolLayer)) ids.push(+id);\n }\n if (symbolLayer) {\n return ids.sort((a_, b_) => {\n const a = this._tiles[a_].tileID;\n const b = this._tiles[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 });\n }\n return ids.sort(compareKeyZoom);\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: number, 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 _reloadTile(id: string | number, 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\n this._loadTile(tile, this._tileLoaded.bind(this, tile, id, state));\n }\n\n _tileLoaded(tile: Tile, id: string | number, previousState: TileState, err: ?Error) {\n if (err) {\n tile.state = 'errored';\n if ((err: any).status !== 404) this._source.fire(new ErrorEvent(err, {tile}));\n // continue to try loading parent/children tiles if a tile doesn't exist (404)\n else this.update(this.transform);\n return;\n }\n\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 this._source.fire(new Event('data', {dataType: 'source', tile, coord: tile.tileID}));\n }\n\n /**\n * For raster terrain source, backfill DEM to eliminate visible tile boundaries\n * @private\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 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 | number): Tile {\n return this._tiles[id];\n }\n\n /**\n * get the zoom level adjusted for the difference in map and source tilesizes\n */\n getZoom(transform: Transform): number {\n return transform.zoom + transform.scaleZoom(transform.tileSize / this._source.tileSize);\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: {[any]: OverscaledTileID},\n zoom: number,\n maxCoveringZoom: number,\n retain: {[any]: OverscaledTileID}\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 for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) {\n const parent = tileID.scaledTo(z);\n if (!parent) return;\n const id = String(parent.key);\n const tile = this._tiles[id];\n if (tile && tile.hasData()) {\n return tile;\n }\n if (this._cache.has(parent)) {\n return this._cache.get(parent);\n }\n }\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 = 5;\n\n const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);\n const maxSize = typeof this._maxTileCacheSize === 'number' ? 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 cppy 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 = {};\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 /**\n * Removes tiles that are outside the viewport and adds new tiles that\n * are inside the viewport.\n */\n update(transform: Transform) {\n this.transform = transform;\n if (!this._sourceLoaded || this._paused) { return; }\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;\n if (!this.used) {\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._source.tileSize,\n minzoom: this._source.minzoom,\n maxzoom: this._source.maxzoom,\n roundZoom: this._source.roundZoom,\n reparseOverscaled: this._source.reparseOverscaled\n });\n\n if (this._source.hasTile) {\n idealTileIDs = idealTileIDs.filter((coord) => (this._source.hasTile: any)(coord));\n }\n }\n\n // Determine the overzooming/underzooming amounts.\n const zoom = (this._source.roundZoom ? Math.round : Math.floor)(this.getZoom(transform));\n const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom);\n const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom);\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 const parentsForFading = {};\n const fadingTiles = {};\n const ids = Object.keys(retain);\n for (const id of ids) {\n const tileID = retain[id];\n assert(tileID.key === +id);\n\n const tile = this._tiles[id];\n if (!tile || tile.fadeEndTime && tile.fadeEndTime <= browser.now()) continue;\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 if (parentTile) {\n this._addTile(parentTile.tileID);\n parentsForFading[parentTile.tileID.key] = parentTile.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 parentsForFading) {\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] = parentsForFading[id];\n }\n }\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\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 = {};\n const checked: {[number]: 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 retain[parentId.key] = parentId;\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 (tile.hasData()) break;\n }\n }\n }\n\n return retain;\n }\n\n /**\n * Add a tile, given its coordinate, to the pyramid.\n * @private\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 = Boolean(tile);\n if (!cached) {\n tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor());\n this._loadTile(tile, this._tileLoaded.bind(this, tile, tileID.key, tile.state));\n }\n\n // Impossible, but silence flow.\n if (!tile) return (null: any);\n\n tile.uses++;\n this._tiles[tileID.key] = tile;\n if (!cached) this._source.fire(new Event('dataloading', {tile, coord: tile.tileID, dataType: 'source'}));\n\n return tile;\n }\n\n _setTileReloadTimer(id: string | number, 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 * @private\n */\n _removeTile(id: string | number) {\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 /**\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 {Array} 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) {\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) => transform.pointCoordinate(p));\n const cameraQueryGeometry = cameraPointQueryGeometry.map((p) => transform.pointCoordinate(p));\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 for (const id in this._tiles) {\n const tile = this._tiles[id];\n if (tile.fadeEndTime !== undefined && tile.fadeEndTime >= browser.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 * @private\n */\n setFeatureState(sourceLayer?: string, feature: number, state: Object) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n this._state.updateState(sourceLayer, feature, state);\n }\n\n /**\n * Resets the value of a particular state key for a feature\n * @private\n */\n removeFeatureState(sourceLayer?: string, feature?: number, key?: string) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n this._state.removeFeatureState(sourceLayer, feature, key);\n }\n\n /**\n * Get the entire state object for a feature\n * @private\n */\n getFeatureState(sourceLayer?: string, feature: number) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n return this._state.getState(sourceLayer, feature);\n }\n}\n\nSourceCache.maxOverzooming = 10;\nSourceCache.maxUnderzooming = 3;\n\nfunction compareKeyZoom(a, b) {\n return ((a % 32) - (b % 32)) || (b - a);\n}\n\nfunction isRasterType(type) {\n return type === 'raster' || type === 'image' || type === 'video';\n}\n\nexport default SourceCache;\n","// @flow\n\nimport window from '../window';\nimport mapboxgl from '../../';\n\nimport type {WorkerInterface} from '../web_worker';\n\nexport default function (): WorkerInterface {\n return (new window.Worker(mapboxgl.workerUrl): any);\n}\n","// @flow\n\nimport WebWorker from './web_worker';\nimport type {WorkerInterface} from './web_worker';\nimport browser from './browser';\n\n/**\n * Constructs a worker pool.\n * @private\n */\nexport default class WorkerPool {\n static workerCount: number;\n\n active: {[number]: boolean};\n workers: Array;\n\n constructor() {\n this.active = {};\n }\n\n acquire(mapId: number): Array {\n if (!this.workers) {\n // Lazily look up the value of mapboxgl.workerCount 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(new WebWorker());\n }\n }\n\n this.active[mapId] = true;\n return this.workers.slice();\n }\n\n release(mapId: number) {\n delete this.active[mapId];\n if (Object.keys(this.active).length === 0) {\n this.workers.forEach((w) => {\n w.terminate();\n });\n this.workers = (null: any);\n }\n }\n}\n\nconst availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2);\nWorkerPool.workerCount = Math.max(Math.min(availableLogicalProcessors, 6), 1);\n","// @flow\n\nimport WorkerPool 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 * @private\n */\nexport default function getGlobalWorkerPool () {\n if (!globalWorkerPool) {\n globalWorkerPool = new WorkerPool();\n }\n return globalWorkerPool;\n}\n","\nexport default ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout'];\n","\nimport refProperties from './util/ref_properties';\n\nfunction deref(layer, parent) {\n const result = {};\n\n for (const k in layer) {\n if (k !== 'ref') {\n result[k] = layer[k];\n }\n }\n\n refProperties.forEach((k) => {\n if (k in parent) {\n result[k] = parent[k];\n }\n });\n\n return result;\n}\n\nexport default derefLayers;\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\n const map = Object.create(null);\n for (let i = 0; i < layers.length; i++) {\n map[layers[i].id] = layers[i];\n }\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\n return layers;\n}\n","\nimport isEqual from './util/deep_equal';\n\nconst operations = {\n\n /*\n * { command: 'setStyle', args: [stylesheet] }\n */\n setStyle: 'setStyle',\n\n /*\n * { command: 'addLayer', args: [layer, 'beforeLayerId'] }\n */\n addLayer: 'addLayer',\n\n /*\n * { command: 'removeLayer', args: ['layerId'] }\n */\n removeLayer: 'removeLayer',\n\n /*\n * { command: 'setPaintProperty', args: ['layerId', 'prop', value] }\n */\n setPaintProperty: 'setPaintProperty',\n\n /*\n * { command: 'setLayoutProperty', args: ['layerId', 'prop', value] }\n */\n setLayoutProperty: 'setLayoutProperty',\n\n /*\n * { command: 'setFilter', args: ['layerId', filter] }\n */\n setFilter: 'setFilter',\n\n /*\n * { command: 'addSource', args: ['sourceId', source] }\n */\n addSource: 'addSource',\n\n /*\n * { command: 'removeSource', args: ['sourceId'] }\n */\n removeSource: 'removeSource',\n\n /*\n * { command: 'setGeoJSONSourceData', args: ['sourceId', data] }\n */\n setGeoJSONSourceData: 'setGeoJSONSourceData',\n\n /*\n * { command: 'setLayerZoomRange', args: ['layerId', 0, 22] }\n */\n setLayerZoomRange: 'setLayerZoomRange',\n\n /*\n * { command: 'setLayerProperty', args: ['layerId', 'prop', value] }\n */\n setLayerProperty: 'setLayerProperty',\n\n /*\n * { command: 'setCenter', args: [[lon, lat]] }\n */\n setCenter: 'setCenter',\n\n /*\n * { command: 'setZoom', args: [zoom] }\n */\n setZoom: 'setZoom',\n\n /*\n * { command: 'setBearing', args: [bearing] }\n */\n setBearing: 'setBearing',\n\n /*\n * { command: 'setPitch', args: [pitch] }\n */\n setPitch: 'setPitch',\n\n /*\n * { command: 'setSprite', args: ['spriteUrl'] }\n */\n setSprite: 'setSprite',\n\n /*\n * { command: 'setGlyphs', args: ['glyphsUrl'] }\n */\n setGlyphs: 'setGlyphs',\n\n /*\n * { command: 'setTransition', args: [transition] }\n */\n setTransition: 'setTransition',\n\n /*\n * { command: 'setLighting', args: [lightProperties] }\n */\n setLight: 'setLight'\n\n};\n\nfunction addSource(sourceId, after, commands) {\n commands.push({ command: operations.addSource, args: [sourceId, after[sourceId]] });\n}\n\nfunction removeSource(sourceId, commands, sourcesRemoved) {\n commands.push({ command: operations.removeSource, args: [sourceId] });\n sourcesRemoved[sourceId] = true;\n}\n\nfunction updateSource(sourceId, after, commands, sourcesRemoved) {\n removeSource(sourceId, commands, sourcesRemoved);\n addSource(sourceId, after, commands);\n}\n\nfunction canUpdateGeoJSON(before, after, sourceId) {\n let prop;\n for (prop in before[sourceId]) {\n if (!before[sourceId].hasOwnProperty(prop)) continue;\n if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n for (prop in after[sourceId]) {\n if (!after[sourceId].hasOwnProperty(prop)) continue;\n if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n return true;\n}\n\nfunction diffSources(before, after, commands, sourcesRemoved) {\n before = before || {};\n after = after || {};\n\n let sourceId;\n\n // look for sources to remove\n for (sourceId in before) {\n if (!before.hasOwnProperty(sourceId)) continue;\n if (!after.hasOwnProperty(sourceId)) {\n removeSource(sourceId, commands, sourcesRemoved);\n }\n }\n\n // look for sources to add/update\n for (sourceId in after) {\n if (!after.hasOwnProperty(sourceId)) continue;\n if (!before.hasOwnProperty(sourceId)) {\n addSource(sourceId, after, commands);\n } else if (!isEqual(before[sourceId], after[sourceId])) {\n if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) {\n commands.push({ command: operations.setGeoJSONSourceData, args: [sourceId, after[sourceId].data] });\n } else {\n // no update command, must remove then add\n updateSource(sourceId, after, commands, sourcesRemoved);\n }\n }\n }\n}\n\nfunction diffLayerPropertyChanges(before, after, commands, layerId, klass, command) {\n before = before || {};\n after = after || {};\n\n let prop;\n\n for (prop in before) {\n if (!before.hasOwnProperty(prop)) continue;\n if (!isEqual(before[prop], after[prop])) {\n commands.push({ command, args: [layerId, prop, after[prop], klass] });\n }\n }\n for (prop in after) {\n if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) continue;\n if (!isEqual(before[prop], after[prop])) {\n commands.push({ command, args: [layerId, prop, after[prop], klass] });\n }\n }\n}\n\nfunction pluckId(layer) {\n return layer.id;\n}\nfunction indexById(group, layer) {\n group[layer.id] = layer;\n return group;\n}\n\nfunction diffLayers(before, after, commands) {\n before = before || [];\n after = after || [];\n\n // order of layers by id\n const beforeOrder = before.map(pluckId);\n const afterOrder = after.map(pluckId);\n\n // index of layer by id\n const beforeIndex = before.reduce(indexById, {});\n const afterIndex = after.reduce(indexById, {});\n\n // track order of layers as if they have been mutated\n const tracker = beforeOrder.slice();\n\n // layers that have been added do not need to be diffed\n const clean = Object.create(null);\n\n let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop;\n\n // remove layers\n for (i = 0, d = 0; i < beforeOrder.length; i++) {\n layerId = beforeOrder[i];\n if (!afterIndex.hasOwnProperty(layerId)) {\n commands.push({ command: operations.removeLayer, args: [layerId] });\n tracker.splice(tracker.indexOf(layerId, d), 1);\n } else {\n // limit where in tracker we need to look for a match\n d++;\n }\n }\n\n // add/reorder layers\n for (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\n if (tracker[tracker.length - 1 - i] === layerId) continue;\n\n if (beforeIndex.hasOwnProperty(layerId)) {\n // remove the layer before we insert at the correct position\n commands.push({ command: operations.removeLayer, args: [layerId] });\n tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);\n } else {\n // limit where in tracker we need to look for a match\n d++;\n }\n\n // add layer at correct position\n insertBeforeLayerId = tracker[tracker.length - i];\n commands.push({ command: operations.addLayer, args: [afterIndex[layerId], insertBeforeLayerId] });\n tracker.splice(tracker.length - i, 0, layerId);\n clean[layerId] = true;\n }\n\n // update layers\n for (i = 0; i < afterOrder.length; i++) {\n layerId = afterOrder[i];\n beforeLayer = beforeIndex[layerId];\n afterLayer = afterIndex[layerId];\n\n // no need to update if previously added (new or moved)\n if (clean[layerId] || isEqual(beforeLayer, afterLayer)) continue;\n\n // If source, source-layer, or type have changes, then remove the layer\n // and add it back 'from scratch'.\n if (!isEqual(beforeLayer.source, afterLayer.source) || !isEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !isEqual(beforeLayer.type, afterLayer.type)) {\n commands.push({ command: operations.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 commands.push({ command: operations.addLayer, args: [afterLayer, insertBeforeLayerId] });\n continue;\n }\n\n // layout, paint, filter, minzoom, maxzoom\n diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty);\n diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty);\n if (!isEqual(beforeLayer.filter, afterLayer.filter)) {\n commands.push({ command: operations.setFilter, args: [layerId, afterLayer.filter] });\n }\n if (!isEqual(beforeLayer.minzoom, afterLayer.minzoom) || !isEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) {\n commands.push({ command: operations.setLayerZoomRange, args: [layerId, afterLayer.minzoom, afterLayer.maxzoom] });\n }\n\n // handle all other layer props, including paint.*\n for (prop in beforeLayer) {\n if (!beforeLayer.hasOwnProperty(prop)) continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);\n } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {\n commands.push({ command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]] });\n }\n }\n for (prop in afterLayer) {\n if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);\n } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {\n commands.push({ command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]] });\n }\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 mapbox-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) return [{ command: operations.setStyle, args: [after] }];\n\n let commands = [];\n\n try {\n // Handle changes to top-level properties\n if (!isEqual(before.version, after.version)) {\n return [{ command: operations.setStyle, args: [after] }];\n }\n if (!isEqual(before.center, after.center)) {\n commands.push({ command: operations.setCenter, args: [after.center] });\n }\n if (!isEqual(before.zoom, after.zoom)) {\n commands.push({ command: operations.setZoom, args: [after.zoom] });\n }\n if (!isEqual(before.bearing, after.bearing)) {\n commands.push({ command: operations.setBearing, args: [after.bearing] });\n }\n if (!isEqual(before.pitch, after.pitch)) {\n commands.push({ command: operations.setPitch, args: [after.pitch] });\n }\n if (!isEqual(before.sprite, after.sprite)) {\n commands.push({ command: operations.setSprite, args: [after.sprite] });\n }\n if (!isEqual(before.glyphs, after.glyphs)) {\n commands.push({ command: operations.setGlyphs, args: [after.glyphs] });\n }\n if (!isEqual(before.transition, after.transition)) {\n commands.push({ command: operations.setTransition, args: [after.transition] });\n }\n if (!isEqual(before.light, after.light)) {\n commands.push({ command: operations.setLight, args: [after.light] });\n }\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\n // First collect the {add,remove}Source commands\n const removeOrAddSourceCommands = [];\n diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);\n\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 (sourcesRemoved[layer.source]) {\n commands.push({ command: operations.removeLayer, args: [layer.id] });\n } else {\n beforeLayers.push(layer);\n }\n });\n }\n commands = commands.concat(removeOrAddSourceCommands);\n\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: operations.setStyle, args: [after] }];\n }\n\n return commands;\n}\n\nexport default diffStyles;\nexport { operations };\n","// @flow\n\n/**\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 *\n * @private\n */\nclass 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: any, 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: any, 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 _insertBoxCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {\n this.boxCells[cellIndex].push(uid);\n }\n\n _insertCircleCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {\n this.circleCells[cellIndex].push(uid);\n }\n\n _query(x1: number, y1: number, x2: number, y2: number, hitTest: boolean, predicate?: any) {\n if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {\n return hitTest ? false : [];\n }\n const result = [];\n if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) {\n if (hitTest) {\n return true;\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 return predicate ? result.filter(predicate) : result;\n } else {\n const queryArgs = {\n hitTest,\n seenUids: { box: {}, circle: {} }\n };\n this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate);\n return hitTest ? result.length > 0 : result;\n }\n }\n\n _queryCircle(x: number, y: number, radius: number, hitTest: boolean, predicate?: any) {\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 hitTest ? 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 = [];\n const queryArgs = {\n hitTest,\n circle: { x, y, radius },\n seenUids: { box: {}, circle: {} }\n };\n this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate);\n return hitTest ? result.length > 0 : result;\n }\n\n query(x1: number, y1: number, x2: number, y2: number, predicate?: any): Array {\n return (this._query(x1, y1, x2, y2, false, predicate): any);\n }\n\n hitTest(x1: number, y1: number, x2: number, y2: number, predicate?: any): boolean {\n return (this._query(x1, y1, x2, y2, true, predicate): any);\n }\n\n hitTestCircle(x: number, y: number, radius: number, predicate?: any): boolean {\n return (this._queryCircle(x, y, radius, true, predicate): any);\n }\n\n _queryCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: any, queryArgs: any, predicate?: any) {\n const seenUids = queryArgs.seenUids;\n const boxCell = this.boxCells[cellIndex];\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 if ((x1 <= bboxes[offset + 2]) &&\n (y1 <= bboxes[offset + 3]) &&\n (x2 >= bboxes[offset + 0]) &&\n (y2 >= bboxes[offset + 1]) &&\n (!predicate || predicate(this.boxKeys[boxUid]))) {\n if (queryArgs.hitTest) {\n result.push(true);\n return true;\n } else {\n result.push({\n key: this.boxKeys[boxUid],\n x1: bboxes[offset],\n y1: bboxes[offset + 1],\n x2: bboxes[offset + 2],\n y2: bboxes[offset + 3]\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 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(this.circleKeys[circleUid]))) {\n if (queryArgs.hitTest) {\n result.push(true);\n return true;\n } else {\n const x = circles[offset];\n const y = circles[offset + 1];\n const radius = circles[offset + 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 }\n }\n }\n }\n }\n\n _queryCellCircle(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: any, queryArgs: any, predicate?: any) {\n const circle = queryArgs.circle;\n const seenUids = queryArgs.seenUids;\n const boxCell = this.boxCells[cellIndex];\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 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(this.boxKeys[boxUid]))) {\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 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(this.circleKeys[circleUid]))) {\n result.push(true);\n return true;\n }\n }\n }\n }\n }\n\n _forEachCell(x1: number, y1: number, x2: number, y2: number, fn: any, arg1: any, arg2?: any, predicate?: any) {\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 _convertToXCellCoord(x: number) {\n return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale)));\n }\n\n _convertToYCellCoord(y: number) {\n return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale)));\n }\n\n _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 _circleAndRectCollide(circleX: number, circleY: number, radius: number, x1: number, y1: number, x2: number, y2: number): 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\nexport default GridIndex;\n","// @flow\n\nimport 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';\nimport { WritingMode } from '../symbol/shaping';\n\nexport { updateLineLabels, hideGlyphs, getLabelPlaneMatrix, getGlCoordMatrix, project, placeFirstAndLastGlyph, xyTransformMat4 };\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 * ## GL coordinate space\n * At the end of everything, the vertex shader needs to produce a position in GL coordinate space,\n * which is (-1, 1) at the top left and (1, -1) in the bottom right.\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 gl coordinates\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 gl coords.\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(point: Point, matrix: mat4) {\n const pos = [point.x, point.y, 0, 1];\n xyTransformMat4(pos, pos, matrix);\n const w = pos[3];\n return {\n point: new Point(pos[0] / w, pos[1] / w),\n signedDistanceFromCamera: w\n };\n}\n\nfunction isVisible(anchorPos: [number, number, number, number],\n clippingBuffer: [number, number]) {\n const x = anchorPos[0] / anchorPos[3];\n const y = anchorPos[1] / anchorPos[3];\n const inPaddedViewport = (\n x >= -clippingBuffer[0] &&\n x <= clippingBuffer[0] &&\n y >= -clippingBuffer[1] &&\n 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\n const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;\n const partiallyEvaluatedSize = symbolSize.evaluateSizeForZoom(sizeData, painter.transform.zoom);\n\n const clippingBuffer = [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: any = placedSymbols.get(s);\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 = [symbol.anchorX, symbol.anchorY, 0, 1];\n vec4.transformMat4(anchorPos, anchorPos, posMatrix);\n\n // Don't bother calculating the correct point for invisible labels.\n if (!isVisible(anchorPos, clippingBuffer)) {\n hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n continue;\n }\n\n const cameraToAnchorDistance = anchorPos[3];\n const perspectiveRatio = 0.5 + 0.5 * (cameraToAnchorDistance / painter.transform.cameraToCenterDistance);\n\n const fontSize = symbolSize.evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol);\n const pitchScaledFontSize = pitchWithMap ?\n fontSize * perspectiveRatio :\n fontSize / perspectiveRatio;\n\n const tileAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);\n const anchorPoint = project(tileAnchorPoint, labelPlaneMatrix).point;\n const projectionCache = {};\n\n const placeUnflipped: any = placeGlyphsAlongLine(symbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix,\n bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio);\n\n useVertical = placeUnflipped.useVertical;\n\n if (placeUnflipped.notEnoughRoom || useVertical ||\n (placeUnflipped.needsFlipping &&\n placeGlyphsAlongLine(symbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix,\n bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio).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\nfunction placeFirstAndLastGlyph(fontScale: number, glyphOffsetArray: GlyphOffsetArray, lineOffsetX: number, lineOffsetY: number, flip: boolean, anchorPoint: Point, tileAnchorPoint: Point, symbol: any, lineVertexArray: SymbolLineVertexArray, labelPlaneMatrix: mat4, projectionCache: any, returnTileDistance: boolean) {\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, anchorPoint, tileAnchorPoint, symbol.segment,\n lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache, returnTileDistance);\n if (!firstPlacedGlyph)\n return null;\n\n const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment,\n lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache, returnTileDistance);\n if (!lastPlacedGlyph)\n return null;\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\nfunction placeGlyphsAlongLine(symbol, fontSize, flip, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio) {\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, anchorPoint, tileAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache, false);\n if (!firstAndLastGlyph) {\n return { notEnoughRoom: true };\n }\n const firstPoint = project(firstAndLastGlyph.first.point, glCoordMatrix).point;\n const lastPoint = project(firstAndLastGlyph.last.point, glCoordMatrix).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 // $FlowFixMe\n placedGlyphs.push(placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment,\n lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache, false));\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(tileAnchorPoint, posMatrix).point;\n const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1);\n // $FlowFixMe\n const tileSegmentEnd = new Point(lineVertexArray.getx(tileVertexIndex), lineVertexArray.gety(tileVertexIndex));\n const projectedVertex = project(tileSegmentEnd, posMatrix);\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 projectTruncatedLineSegment(tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix);\n\n const orientationChange = requiresOrientationChange(symbol.writingMode, a, b, aspectRatio);\n if (orientationChange) {\n return orientationChange;\n }\n }\n // $FlowFixMe\n const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment,\n symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, lineVertexArray, labelPlaneMatrix, projectionCache, false);\n if (!singleGlyph)\n return { notEnoughRoom: true };\n\n placedGlyphs = [singleGlyph];\n }\n\n for (const glyph: any of placedGlyphs) {\n addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle);\n }\n return {};\n}\n\nfunction projectTruncatedLineSegment(previousTilePoint: Point, currentTilePoint: Point, previousProjectedPoint: Point, minimumLength: number, projectionMatrix: mat4) {\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 projectedUnitVertex = project(previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()), projectionMatrix).point;\n const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex);\n\n return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag()));\n}\n\nfunction placeGlyphAlongLine(offsetX: number,\n lineOffsetX: number,\n lineOffsetY: number,\n flip: boolean,\n anchorPoint: Point,\n tileAnchorPoint: Point,\n anchorSegment: number,\n lineStartIndex: number,\n lineEndIndex: number,\n lineVertexArray: SymbolLineVertexArray,\n labelPlaneMatrix: mat4,\n projectionCache: {[number]: Point},\n returnTileDistance: boolean) {\n\n const combinedOffsetX = flip ?\n offsetX - lineOffsetX :\n offsetX + lineOffsetX;\n\n let dir = 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 dir *= -1;\n angle = Math.PI;\n }\n\n if (dir < 0) angle += Math.PI;\n\n let currentIndex = dir > 0 ?\n lineStartIndex + anchorSegment :\n lineStartIndex + anchorSegment + 1;\n\n const initialIndex = currentIndex;\n let current = anchorPoint;\n let prev = anchorPoint;\n let distanceToPrev = 0;\n let currentSegmentDistance = 0;\n const absOffsetX = Math.abs(combinedOffsetX);\n\n while (distanceToPrev + currentSegmentDistance <= absOffsetX) {\n currentIndex += dir;\n\n // offset does not fit on the projected line\n if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex)\n return null;\n\n prev = current;\n\n current = projectionCache[currentIndex];\n if (current === undefined) {\n const currentVertex = new Point(lineVertexArray.getx(currentIndex), lineVertexArray.gety(currentIndex));\n const projection = project(currentVertex, labelPlaneMatrix);\n if (projection.signedDistanceFromCamera > 0) {\n current = projectionCache[currentIndex] = projection.point;\n } else {\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 = currentIndex - dir;\n const previousTilePoint = distanceToPrev === 0 ?\n tileAnchorPoint :\n new Point(lineVertexArray.getx(previousLineVertexIndex), lineVertexArray.gety(previousLineVertexIndex));\n // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment\n current = projectTruncatedLineSegment(previousTilePoint, currentVertex, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix);\n }\n }\n\n distanceToPrev += currentSegmentDistance;\n currentSegmentDistance = prev.dist(current);\n }\n\n // The point is on the current segment. Interpolate to find it.\n const segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance;\n const prevToCurrent = current.sub(prev);\n const p = prevToCurrent.mult(segmentInterpolationT)._add(prev);\n\n // offset the point from the line to text-offset and icon-offset\n p._add(prevToCurrent._unit()._perp()._mult(lineOffsetY * dir));\n\n const segmentAngle = angle + Math.atan2(current.y - prev.y, current.x - prev.x);\n\n return {\n point: p,\n angle: segmentAngle,\n tileDistance: returnTileDistance ?\n {\n prevTileDistance: (currentIndex - dir) === initialIndex ? 0 : lineVertexArray.gettileUnitDistanceFromAnchor(currentIndex - dir),\n lastSegmentViewportDistance: absOffsetX - distanceToPrev\n } : null\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","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport * as intersectionTests from '../util/intersection_tests';\nimport Grid from './grid_index';\nimport { mat4 } from 'gl-matrix';\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';\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.\nconst viewportPadding = 100;\n\n/**\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 *\n * @private\n */\nclass CollisionIndex {\n grid: Grid;\n ignoredGrid: Grid;\n transform: Transform;\n pitchfactor: number;\n screenRightBoundary: number;\n screenBottomBoundary: number;\n gridRightBoundary: number;\n gridBottomBoundary: number;\n\n constructor(\n transform: Transform,\n grid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25),\n ignoredGrid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)\n ) {\n this.transform = transform;\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\n placeCollisionBox(collisionBox: SingleCollisionBox, allowOverlap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroupPredicate?: any): { box: Array, offscreen: boolean } {\n const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, collisionBox.anchorPointX, collisionBox.anchorPointY);\n const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;\n const tlX = collisionBox.x1 * tileToViewport + projectedPoint.point.x;\n const tlY = collisionBox.y1 * tileToViewport + projectedPoint.point.y;\n const brX = collisionBox.x2 * tileToViewport + projectedPoint.point.x;\n const brY = collisionBox.y2 * tileToViewport + projectedPoint.point.y;\n\n if (!this.isInsideGrid(tlX, tlY, brX, brY) ||\n (!allowOverlap && this.grid.hitTest(tlX, tlY, brX, brY, collisionGroupPredicate))) {\n return {\n box: [],\n offscreen: false\n };\n }\n\n return {\n box: [tlX, tlY, brX, brY],\n offscreen: this.isOffscreen(tlX, tlY, brX, brY)\n };\n }\n\n approximateTileDistance(tileDistance: any, lastSegmentAngle: number, pixelsToTileUnits: number, cameraToAnchorDistance: number, pitchWithMap: boolean): number {\n // This is a quick and dirty solution for chosing which collision circles to use (since collision circles are\n // laid out in tile units). Ideally, I think we should generate collision circles on the fly in viewport coordinates\n // at the time we do collision detection.\n // See https://github.com/mapbox/mapbox-gl-js/issues/5474\n\n // incidenceStretch is the ratio of how much y space a label takes up on a tile while drawn perpendicular to the viewport vs\n // how much space it would take up if it were drawn flat on the tile\n // Using law of sines, camera_to_anchor/sin(ground_angle) = camera_to_center/sin(incidence_angle)\n // Incidence angle 90 -> head on, sin(incidence_angle) = 1, no stretch\n // Incidence angle 1 -> very oblique, sin(incidence_angle) =~ 0, lots of stretch\n // ground_angle = u_pitch + PI/2 -> sin(ground_angle) = cos(u_pitch)\n // incidenceStretch = 1 / sin(incidenceAngle)\n\n const incidenceStretch = pitchWithMap ? 1 : cameraToAnchorDistance / this.pitchfactor;\n const lastSegmentTile = tileDistance.lastSegmentViewportDistance * pixelsToTileUnits;\n return tileDistance.prevTileDistance +\n lastSegmentTile +\n (incidenceStretch - 1) * lastSegmentTile * Math.abs(Math.sin(lastSegmentAngle));\n }\n\n placeCollisionCircles(collisionCircles: Array,\n allowOverlap: boolean,\n scale: number,\n textPixelRatio: number,\n symbol: any,\n lineVertexArray: SymbolLineVertexArray,\n glyphOffsetArray: GlyphOffsetArray,\n fontSize: number,\n posMatrix: mat4,\n labelPlaneMatrix: mat4,\n showCollisionCircles: boolean,\n pitchWithMap: boolean,\n collisionGroupPredicate?: any): { circles: Array, offscreen: boolean } {\n const placedCollisionCircles = [];\n\n const projectedAnchor = this.projectAnchor(posMatrix, symbol.anchorX, symbol.anchorY);\n\n const projectionCache = {};\n const fontScale = fontSize / 24;\n const lineOffsetX = symbol.lineOffsetX * fontSize;\n const lineOffsetY = symbol.lineOffsetY * fontSize;\n\n const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);\n // projection.project generates NDC coordinates, as opposed to the\n // pixel-based grid coordinates generated by this.projectPoint\n const labelPlaneAnchorPoint =\n projection.project(tileUnitAnchorPoint, labelPlaneMatrix).point;\n const firstAndLastGlyph = projection.placeFirstAndLastGlyph(\n fontScale,\n glyphOffsetArray,\n lineOffsetX,\n lineOffsetY,\n /*flip*/ false,\n labelPlaneAnchorPoint,\n tileUnitAnchorPoint,\n symbol,\n lineVertexArray,\n labelPlaneMatrix,\n projectionCache,\n /*return tile distance*/ true);\n\n let collisionDetected = false;\n let inGrid = false;\n let entirelyOffscreen = true;\n\n const tileToViewport = projectedAnchor.perspectiveRatio * textPixelRatio;\n // pixelsToTileUnits is used for translating line geometry to tile units\n // ... so we care about 'scale' but not 'perspectiveRatio'\n // equivalent to pixel_to_tile_units\n const pixelsToTileUnits = 1 / (textPixelRatio * scale);\n\n let firstTileDistance = 0, lastTileDistance = 0;\n if (firstAndLastGlyph) {\n firstTileDistance = this.approximateTileDistance(firstAndLastGlyph.first.tileDistance, firstAndLastGlyph.first.angle, pixelsToTileUnits, projectedAnchor.cameraDistance, pitchWithMap);\n lastTileDistance = this.approximateTileDistance(firstAndLastGlyph.last.tileDistance, firstAndLastGlyph.last.angle, pixelsToTileUnits, projectedAnchor.cameraDistance, pitchWithMap);\n }\n\n for (let k = 0; k < collisionCircles.length; k += 5) {\n const anchorPointX = collisionCircles[k];\n const anchorPointY = collisionCircles[k + 1];\n const tileUnitRadius = collisionCircles[k + 2];\n const boxSignedDistanceFromAnchor = collisionCircles[k + 3];\n if (!firstAndLastGlyph ||\n (boxSignedDistanceFromAnchor < -firstTileDistance) ||\n (boxSignedDistanceFromAnchor > lastTileDistance)) {\n // The label either doesn't fit on its line or we\n // don't need to use this circle because the label\n // doesn't extend this far. Either way, mark the circle unused.\n markCollisionCircleUsed(collisionCircles, k, false);\n continue;\n }\n\n const projectedPoint = this.projectPoint(posMatrix, anchorPointX, anchorPointY);\n const radius = tileUnitRadius * tileToViewport;\n\n const atLeastOneCirclePlaced = placedCollisionCircles.length > 0;\n if (atLeastOneCirclePlaced) {\n const dx = projectedPoint.x - placedCollisionCircles[placedCollisionCircles.length - 4];\n const dy = projectedPoint.y - placedCollisionCircles[placedCollisionCircles.length - 3];\n // The circle edges touch when the distance between their centers is 2x the radius\n // When the distance is 1x the radius, they're doubled up, and we could remove\n // every other circle while keeping them all in touch.\n // We actually start removing circles when the distance is √2x the radius:\n // thinning the number of circles as much as possible is a major performance win,\n // and the small gaps introduced don't make a very noticeable difference.\n const placedTooDensely = radius * radius * 2 > dx * dx + dy * dy;\n if (placedTooDensely) {\n const atLeastOneMoreCircle = (k + 8) < collisionCircles.length;\n if (atLeastOneMoreCircle) {\n const nextBoxDistanceToAnchor = collisionCircles[k + 8];\n if ((nextBoxDistanceToAnchor > -firstTileDistance) &&\n (nextBoxDistanceToAnchor < lastTileDistance)) {\n // Hide significantly overlapping circles, unless this is the last one we can\n // use, in which case we want to keep it in place even if it's tightly packed\n // with the one before it.\n markCollisionCircleUsed(collisionCircles, k, false);\n continue;\n }\n }\n }\n }\n const collisionBoxArrayIndex = k / 5;\n placedCollisionCircles.push(projectedPoint.x, projectedPoint.y, radius, collisionBoxArrayIndex);\n markCollisionCircleUsed(collisionCircles, k, true);\n\n const x1 = projectedPoint.x - radius;\n const y1 = projectedPoint.y - radius;\n const x2 = projectedPoint.x + radius;\n const y2 = projectedPoint.y + radius;\n entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2);\n inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2);\n\n if (!allowOverlap) {\n if (this.grid.hitTestCircle(projectedPoint.x, projectedPoint.y, radius, collisionGroupPredicate)) {\n if (!showCollisionCircles) {\n return {\n circles: [],\n offscreen: false\n };\n } else {\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 }\n }\n }\n }\n\n return {\n circles: (collisionDetected || !inGrid) ? [] : placedCollisionCircles,\n offscreen: entirelyOffscreen\n };\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 * @private\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, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {\n const grid = ignorePlacement ? this.ignoredGrid : this.grid;\n\n const key = { bucketInstanceId, featureIndex, collisionGroupID };\n grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]);\n }\n\n insertCollisionCircles(collisionCircles: Array, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {\n const grid = ignorePlacement ? this.ignoredGrid : this.grid;\n\n const key = { bucketInstanceId, featureIndex, collisionGroupID };\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 projectAnchor(posMatrix: mat4, x: number, y: number) {\n const p = [x, y, 0, 1];\n projection.xyTransformMat4(p, p, posMatrix);\n return {\n perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / p[3]),\n cameraDistance: p[3]\n };\n }\n\n projectPoint(posMatrix: mat4, x: number, y: number) {\n const p = [x, y, 0, 1];\n projection.xyTransformMat4(p, p, posMatrix);\n return new Point(\n (((p[0] / p[3] + 1) / 2) * this.transform.width) + viewportPadding,\n (((-p[1] / p[3] + 1) / 2) * this.transform.height) + viewportPadding\n );\n }\n\n projectAndGetPerspectiveRatio(posMatrix: mat4, x: number, y: number) {\n const p = [x, y, 0, 1];\n projection.xyTransformMat4(p, p, posMatrix);\n const a = new Point(\n (((p[0] / p[3] + 1) / 2) * this.transform.width) + viewportPadding,\n (((-p[1] / p[3] + 1) / 2) * this.transform.height) + viewportPadding\n );\n return {\n point: a,\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 / p[3])\n };\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\nfunction markCollisionCircleUsed(collisionCircles: Array, index: number, used: boolean) {\n collisionCircles[index + 4] = used ? 1 : 0;\n}\n\nexport default CollisionIndex;\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}","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","/**\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","// @flow\n\nimport Anchor from './anchor';\n\nimport { getAnchors, getCenterAnchor } from './get_anchors';\nimport clipLine from './clip_line';\nimport { shapeText, shapeIcon, WritingMode } 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 classifyRings from '../util/classify_rings';\nimport EXTENT from '../data/extent';\nimport SymbolBucket from '../data/bucket/symbol_bucket';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport {SIZE_PACK_FACTOR} from './symbol_size';\nimport ONE_EM from './one_em';\n\nimport type {Shaping, PositionedIcon, TextJustify} from './shaping';\nimport type {CollisionBoxArray} from '../data/array_types';\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';\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\nexport type TextAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\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;\n\nexport function evaluateRadialOffset(anchor: TextAnchor, radialOffset: number) {\n let x = 0, y = 0;\n // solve for r where r^2 + r^2 = radialOffset^2\n const hypotenuse = radialOffset / Math.sqrt(2);\n\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\nexport function performSymbolLayout(bucket: SymbolBucket,\n glyphMap: {[string]: {[number]: ?StyleGlyph}},\n glyphPositions: {[string]: {[number]: GlyphPosition}},\n imageMap: {[string]: StyleImage},\n imagePositions: {[string]: ImagePosition},\n showCollisionBoxes: boolean) {\n bucket.createArrays();\n\n const tileSize = 512 * bucket.overscaling;\n bucket.tilePixelRatio = EXTENT / tileSize;\n bucket.compareText = {};\n bucket.iconsNeedLinear = false;\n\n const layout = bucket.layers[0].layout;\n const unevaluatedLayoutValues = bucket.layers[0]._unevaluatedLayout._values;\n\n const sizes = {};\n\n if (bucket.textSizeData.kind === 'composite') {\n const {minZoom, maxZoom} = bucket.textSizeData;\n sizes.compositeTextSizes = [\n unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom)),\n unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom))\n ];\n }\n\n if (bucket.iconSizeData.kind === 'composite') {\n const {minZoom, maxZoom} = bucket.iconSizeData;\n sizes.compositeIconSizes = [\n unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom)),\n unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom))\n ];\n }\n\n sizes.layoutTextSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(bucket.zoom + 1));\n sizes.layoutIconSize = unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(bucket.zoom + 1));\n sizes.textMaxSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18));\n\n const lineHeight = layout.get('text-line-height') * ONE_EM;\n const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point';\n const keepUpright = layout.get('text-keep-upright');\n\n for (const feature of bucket.features) {\n const fontstack = layout.get('text-font').evaluate(feature, {}).join(',');\n const glyphPositionMap = glyphPositions;\n\n const shapedTextOrientations = {\n horizontal: {},\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, {}) * ONE_EM;\n const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0;\n\n const textAnchor = layout.get('text-anchor').evaluate(feature, {});\n const variableTextAnchor = layout.get('text-variable-anchor');\n const radialOffset = layout.get('text-radial-offset').evaluate(feature, {});\n\n if (!variableTextAnchor) {\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 = evaluateRadialOffset(textAnchor, radialOffset * ONE_EM);\n } else {\n textOffset = (layout.get('text-offset').evaluate(feature, {}).map(t => t * ONE_EM): any);\n }\n }\n\n let textJustify = textAlongLine ?\n \"center\" :\n layout.get('text-justify').evaluate(feature, {});\n\n const maxWidth = layout.get('symbol-placement') === 'point' ?\n layout.get('text-max-width').evaluate(feature, {}) * ONE_EM :\n 0;\n\n const addVerticalShapingForPointLabelIfNeeded = () => {\n if (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, glyphMap, fontstack, maxWidth, lineHeight, textAnchor,\n 'left', spacingIfAllowed, textOffset, WritingMode.vertical, true);\n }\n };\n\n // If this layer uses text-variable-anchor, generate shapings for all justification possibilities.\n if (!textAlongLine && variableTextAnchor) {\n const justifications = textJustify === \"auto\" ?\n variableTextAnchor.map(a => getAnchorJustification(a)) :\n [textJustify];\n\n let singleLine = false;\n for (let i = 0; i < justifications.length; i++) {\n const justification: TextJustify = justifications[i];\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, glyphMap, fontstack, maxWidth, lineHeight, 'center',\n justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false);\n if (shaping) {\n shapedTextOrientations.horizontal[justification] = shaping;\n singleLine = shaping.lineCount === 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, glyphMap, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed,\n textOffset, WritingMode.horizontal, false);\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, glyphMap, fontstack, maxWidth, lineHeight, textAnchor, textJustify,\n spacingIfAllowed, textOffset, WritingMode.vertical, false);\n }\n }\n\n }\n\n let shapedIcon;\n if (feature.icon) {\n const image = imageMap[feature.icon];\n if (image) {\n shapedIcon = shapeIcon(\n imagePositions[feature.icon],\n layout.get('icon-offset').evaluate(feature, {}),\n layout.get('icon-anchor').evaluate(feature, {}));\n if (bucket.sdfIcons === undefined) {\n bucket.sdfIcons = image.sdf;\n } else if (bucket.sdfIcons !== image.sdf) {\n warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer');\n }\n if (image.pixelRatio !== bucket.pixelRatio) {\n bucket.iconsNeedLinear = true;\n } else if (layout.get('icon-rotate').constantOr(1) !== 0) {\n bucket.iconsNeedLinear = true;\n }\n }\n }\n\n if (Object.keys(shapedTextOrientations.horizontal).length || shapedIcon) {\n addFeature(bucket, feature, shapedTextOrientations, shapedIcon, glyphPositionMap, sizes, textOffset);\n }\n }\n\n if (showCollisionBoxes) {\n 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 * @private\n */\nfunction addFeature(bucket: SymbolBucket,\n feature: SymbolFeature,\n shapedTextOrientations: any,\n shapedIcon: PositionedIcon | void,\n glyphPositionMap: {[string]: {[number]: GlyphPosition}},\n sizes: Sizes,\n textOffset: [number, number]) {\n const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {});\n const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {});\n\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\n const layout = bucket.layers[0].layout;\n const iconOffset = layout.get('icon-offset').evaluate(feature, {});\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 = layout.get('icon-padding') * bucket.tilePixelRatio,\n textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI,\n textAlongLine = layout.get('text-rotation-alignment') === 'map' && 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 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\n addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, bucket.layers[0],\n bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index,\n textBoxScale, textPadding, textAlongLine, textOffset,\n iconBoxScale, iconPadding, iconAlongLine, iconOffset,\n feature, glyphPositionMap, sizes);\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\nconst MAX_PACKED_SIZE = 65535;\n\nfunction addTextVertices(bucket: SymbolBucket,\n anchor: Point,\n shapedText: Shaping,\n layer: SymbolStyleLayer,\n textAlongLine: boolean,\n feature: SymbolFeature,\n textOffset: [number, number],\n lineArray: {lineStartIndex: number, lineLength: number},\n writingMode: number,\n placementTypes: Array<'vertical' | 'center' | 'left' | 'right'>,\n placedTextSymbolIndices: {[string]: number},\n glyphPositionMap: {[string]: {[number]: GlyphPosition}},\n sizes: Sizes) {\n const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset,\n layer, textAlongLine, feature, glyphPositionMap, 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 >= 256. Reduce your \"text-size\".`);\n }\n } else if (sizeData.kind === 'composite') {\n textSizeData = [\n SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}),\n SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {})\n ];\n if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"text-size\" is >= 256. 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\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(horizontalShaping: {[TextJustify]: Shaping}): 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: any in horizontalShaping) {\n return horizontalShaping[justification];\n }\n return null;\n}\n\n/**\n * Add a single label & icon placement.\n *\n * @private\n */\nfunction addSymbol(bucket: SymbolBucket,\n anchor: Anchor,\n line: Array,\n shapedTextOrientations: any,\n shapedIcon: PositionedIcon | void,\n layer: SymbolStyleLayer,\n collisionBoxArray: CollisionBoxArray,\n featureIndex: number,\n sourceLayerIndex: number,\n bucketIndex: number,\n textBoxScale: number,\n textPadding: number,\n textAlongLine: boolean,\n textOffset: [number, number],\n iconBoxScale: number,\n iconPadding: number,\n iconAlongLine: boolean,\n iconOffset: [number, number],\n feature: SymbolFeature,\n glyphPositionMap: {[string]: {[number]: GlyphPosition}},\n sizes: Sizes) {\n const lineArray = bucket.addToLineVertexArray(anchor, line);\n\n let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature;\n\n let numIconVertices = 0;\n let numHorizontalGlyphVertices = 0;\n let numVerticalGlyphVertices = 0;\n const placedTextSymbolIndices = {};\n let key = murmur3('');\n const radialTextOffset = (layer.layout.get('text-radial-offset').evaluate(feature, {}) || 0) * ONE_EM;\n\n if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {\n const textRotation = layer.layout.get('text-rotate').evaluate(feature, {});\n const verticalTextRotation = textRotation + 90.0;\n const verticalShaping = shapedTextOrientations.vertical;\n verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, line, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, bucket.overscaling, verticalTextRotation);\n }\n\n for (const justification: any in shapedTextOrientations.horizontal) {\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, {});\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, line, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, bucket.overscaling, textRotate);\n }\n\n const singleLine = shaping.lineCount === 1;\n numHorizontalGlyphVertices += addTextVertices(\n bucket, anchor, shaping, layer, textAlongLine, feature, textOffset, lineArray,\n shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly,\n singleLine ? (Object.keys(shapedTextOrientations.horizontal): any) : [justification],\n placedTextSymbolIndices, glyphPositionMap, sizes);\n\n if (singleLine) {\n break;\n }\n }\n\n if (shapedTextOrientations.vertical) {\n numVerticalGlyphVertices += addTextVertices(\n bucket, anchor, shapedTextOrientations.vertical, layer, textAlongLine, feature,\n textOffset, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, glyphPositionMap, sizes);\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 if (shapedIcon) {\n const iconQuads = getIconQuads(anchor, shapedIcon, layer,\n iconAlongLine, getDefaultHorizontalShaping(shapedTextOrientations.horizontal),\n feature);\n const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {});\n iconCollisionFeature = new CollisionFeature(collisionBoxArray, line, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/false, bucket.overscaling, 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 >= 256. Reduce your \"icon-size\".`);\n }\n } else if (sizeData.kind === 'composite') {\n iconSizeData = [\n SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}),\n SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {})\n ];\n if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"icon-size\" is >= 256. Reduce your \"icon-size\".`);\n }\n }\n\n bucket.addSymbols(\n bucket.icon,\n iconQuads,\n iconSizeData,\n iconOffset,\n iconAlongLine,\n feature,\n false,\n anchor,\n lineArray.lineStartIndex,\n lineArray.lineLength);\n }\n\n const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\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 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 key,\n textBoxStartIndex,\n textBoxEndIndex,\n verticalTextBoxStartIndex,\n verticalTextBoxEndIndex,\n iconBoxStartIndex,\n iconBoxEndIndex,\n featureIndex,\n numHorizontalGlyphVertices,\n numVerticalGlyphVertices,\n numIconVertices,\n 0,\n textBoxScale,\n radialTextOffset);\n}\n\nfunction anchorIsTooClose(bucket: any, 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","// @flow\n\nimport 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 * @private\n */\nexport default function(tile: {tileID: OverscaledTileID, tileSize: number}, pixelValue: number, z: number): number {\n return pixelValue * (EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ)));\n}\n","// @flow\n\nimport CollisionIndex from './collision_index';\nimport EXTENT from '../data/extent';\nimport * as symbolSize from './symbol_size';\nimport * as projection from './projection';\nimport { getAnchorJustification, evaluateRadialOffset } from './symbol_layout';\nimport { getAnchorAlignment, WritingMode } from './shaping';\nimport assert from 'assert';\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';\n\nimport type Tile from '../source/tile';\nimport type SymbolBucket, { CollisionArrays, SingleCollisionBox } from '../data/bucket/symbol_bucket';\nimport type {mat4} from 'gl-matrix';\nimport type {CollisionBoxArray, CollisionVertexArray, SymbolInstance} from '../data/array_types';\nimport type FeatureIndex from '../data/feature_index';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport type {TextAnchor} from './symbol_layout';\n\nclass OpacityState {\n opacity: number;\n placed: boolean;\n constructor(prevState: ?OpacityState, increment: number, placed: boolean, skipFade: ?boolean) {\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) {\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\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 = { ID: number, predicate?: any };\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 calculateVariableLayoutOffset(anchor: TextAnchor, width: number, height: number, radialOffset: number, textBoxScale: number): Point {\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);\n const shiftX = -(horizontalAlign - 0.5) * width;\n const shiftY = -(verticalAlign - 0.5) * height;\n const offset = evaluateRadialOffset(anchor, radialOffset);\n return new Point(\n shiftX + offset[0] * textBoxScale,\n shiftY + offset[1] * textBoxScale\n );\n}\n\nfunction shiftVariableCollisionBox(collisionBox: SingleCollisionBox,\n shiftX: number, shiftY: number,\n rotateWithMap: boolean, pitchWithMap: boolean,\n angle: number) {\n const {x1, x2, y1, y2, anchorPointX, anchorPointY} = collisionBox;\n const rotatedOffset = new Point(shiftX, shiftY);\n if (rotateWithMap) {\n rotatedOffset._rotate(pitchWithMap ? angle : -angle);\n }\n return {\n x1: x1 + rotatedOffset.x,\n y1: y1 + rotatedOffset.y,\n x2: x2 + rotatedOffset.x,\n y2: y2 + rotatedOffset.y,\n // symbol anchor point stays the same regardless of text-anchor\n anchorPointX,\n anchorPointY\n };\n}\n\nexport type VariableOffset = {\n radialOffset: number,\n width: number,\n height: number,\n anchor: TextAnchor,\n textBoxScale: number,\n prevAnchor?: TextAnchor\n};\n\nexport type CrossTileID = string | number;\n\nexport class Placement {\n transform: Transform;\n collisionIndex: CollisionIndex;\n placements: { [CrossTileID]: JointPlacement };\n opacities: { [CrossTileID]: JointOpacityState };\n variableOffsets: {[CrossTileID]: VariableOffset };\n placedOrientations: {[CrossTileID]: number };\n commitTime: number;\n lastPlacementChangeTime: number;\n stale: boolean;\n fadeDuration: number;\n retainedQueryData: {[number]: RetainedQueryData};\n collisionGroups: CollisionGroups;\n prevPlacement: ?Placement;\n\n constructor(transform: Transform, fadeDuration: number, crossSourceCollisions: boolean, prevPlacement?: Placement) {\n this.transform = transform.clone();\n this.collisionIndex = new CollisionIndex(this.transform);\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\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 placeLayerTile(styleLayer: StyleLayer, tile: Tile, showCollisionBoxes: boolean, seenCrossTileIDs: { [string | number]: boolean }) {\n const symbolBucket = ((tile.getBucket(styleLayer): any): 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\n const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ);\n const textPixelRatio = tile.tileSize / EXTENT;\n\n const posMatrix = this.transform.calculatePosMatrix(tile.tileID.toUnwrapped());\n\n const textLabelPlaneMatrix = projection.getLabelPlaneMatrix(posMatrix,\n layout.get('text-pitch-alignment') === 'map',\n layout.get('text-rotation-alignment') === 'map',\n this.transform,\n pixelsToTileUnits(tile, 1, this.transform.zoom));\n\n const iconLabelPlaneMatrix = projection.getLabelPlaneMatrix(posMatrix,\n layout.get('icon-pitch-alignment') === 'map',\n layout.get('icon-rotation-alignment') === 'map',\n this.transform,\n pixelsToTileUnits(tile, 1, this.transform.zoom));\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 this.placeLayerBucket(symbolBucket, posMatrix, textLabelPlaneMatrix, iconLabelPlaneMatrix, scale, textPixelRatio,\n showCollisionBoxes, tile.holdingForFade(), seenCrossTileIDs, collisionBoxArray);\n }\n\n attemptAnchorPlacement(anchor: TextAnchor, textBox: SingleCollisionBox, width: number, height: number,\n radialTextOffset: number, textBoxScale: number, rotateWithMap: boolean,\n pitchWithMap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroup: CollisionGroup,\n textAllowOverlap: boolean, symbolInstance: SymbolInstance, bucket: SymbolBucket, orientation: number): ?{ box: Array, offscreen: boolean } {\n\n const shift = calculateVariableLayoutOffset(anchor, width, height, radialTextOffset, textBoxScale);\n\n const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(\n shiftVariableCollisionBox(\n textBox, shift.x, shift.y,\n rotateWithMap, pitchWithMap, this.transform.angle),\n textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);\n\n if (placedGlyphBoxes.box.length > 0) {\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 assert(symbolInstance.crossTileID !== 0);\n this.variableOffsets[symbolInstance.crossTileID] = {\n radialOffset: radialTextOffset,\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 placedGlyphBoxes;\n }\n }\n\n placeLayerBucket(bucket: SymbolBucket, posMatrix: mat4, textLabelPlaneMatrix: mat4, iconLabelPlaneMatrix: mat4,\n scale: number, textPixelRatio: number, showCollisionBoxes: boolean, holdingForFade: boolean, seenCrossTileIDs: { [string | number]: boolean },\n collisionBoxArray: ?CollisionBoxArray) {\n const layout = bucket.layers[0].layout;\n const partiallyEvaluatedTextSize = symbolSize.evaluateSizeForZoom(bucket.textSizeData, this.transform.zoom);\n const textOptional = layout.get('text-optional');\n const iconOptional = layout.get('icon-optional');\n const textAllowOverlap = layout.get('text-allow-overlap');\n const iconAllowOverlap = layout.get('icon-allow-overlap');\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 = textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || iconOptional);\n const alwaysShowIcon = iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || textOptional);\n\n const collisionGroup = this.collisionGroups.get(bucket.sourceID);\n\n const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\n const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y';\n\n if (!bucket.collisionArrays && collisionBoxArray) {\n bucket.deserializeCollisionBoxes(collisionBoxArray);\n }\n\n const placeSymbol = (symbolInstance: SymbolInstance, collisionArrays: CollisionArrays) => {\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\n let placed = { box: null, offscreen: null };\n let placedVertical = { box: null, offscreen: null };\n\n let placedGlyphBoxes = null;\n let placedGlyphCircles = null;\n let placedIconBoxes = null;\n let textFeatureIndex = 0;\n let verticalTextFeatureIndex = 0;\n let iconFeatureIndex = 0;\n\n if (collisionArrays.textFeatureIndex) {\n textFeatureIndex = collisionArrays.textFeatureIndex;\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 placedVertical = placed;\n } else {\n placed = placeHorizontalFn();\n }\n if (placed && placed.box && placed.box.length) break;\n }\n } else {\n placed = placeHorizontalFn();\n }\n };\n\n if (!layout.get('text-variable-anchor')) {\n const placeBox = (collisionTextBox, orientation) => {\n const placedFeature = this.collisionIndex.placeCollisionBox(collisionTextBox, layout.get('text-allow-overlap'),\n textPixelRatio, posMatrix, collisionGroup.predicate);\n if (placedFeature && placedFeature.box && placedFeature.box.length) {\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.box && placed.box.length);\n\n } else {\n let anchors = layout.get('text-variable-anchor');\n\n // If this symbol was in the last placement, shift the previously used\n // anchor to the front of the anchor list, only if the previous anchor\n // is still in the anchor list\n if (this.prevPlacement && this.prevPlacement.variableOffsets[symbolInstance.crossTileID]) {\n const prevOffsets = this.prevPlacement.variableOffsets[symbolInstance.crossTileID];\n if (anchors.indexOf(prevOffsets.anchor) > 0) {\n anchors = anchors.filter(anchor => anchor !== prevOffsets.anchor);\n anchors.unshift(prevOffsets.anchor);\n }\n }\n\n const placeBoxForVariableAnchors = (collisionTextBox, orientation) => {\n const width = collisionTextBox.x2 - collisionTextBox.x1;\n const height = collisionTextBox.y2 - collisionTextBox.y1;\n const textBoxScale = symbolInstance.textBoxScale;\n\n let placedBox: ?{ box: Array, offscreen: boolean } = { box: [], offscreen: false };\n const placementAttempts = textAllowOverlap ? anchors.length * 2 : anchors.length;\n for (let i = 0; i < placementAttempts; ++i) {\n const anchor = anchors[i % anchors.length];\n const allowOverlap = (i >= anchors.length);\n placedBox = this.attemptAnchorPlacement(\n anchor, collisionTextBox, width, height, symbolInstance.radialTextOffset,\n textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix,\n collisionGroup, allowOverlap, symbolInstance, bucket, orientation);\n\n if (placedBox && placedBox.box && placedBox.box.length) {\n placeText = true;\n break;\n }\n }\n\n return placedBox;\n };\n\n const placeHorizontal = () => {\n return placeBoxForVariableAnchors(textBox, WritingMode.horizontal);\n };\n\n const placeVertical = () => {\n const verticalTextBox = collisionArrays.verticalTextBox;\n const wasPlaced = placed && placed.box && placed.box.length;\n if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {\n return placeBoxForVariableAnchors(verticalTextBox, WritingMode.vertical);\n }\n return { box: null, offscreen: null };\n };\n\n placeTextForPlacementModes(placeHorizontal, placeVertical);\n\n if (placed) {\n placeText = placed.box;\n offscreen = placed.offscreen;\n }\n\n const prevOrientation = updatePreviousOrientationIfNotPlaced(placed && placed.box);\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.box && placedGlyphBoxes.box.length > 0;\n\n offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen;\n const textCircles = collisionArrays.textCircles;\n if (textCircles) {\n const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex);\n const fontSize = symbolSize.evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol);\n placedGlyphCircles = this.collisionIndex.placeCollisionCircles(textCircles,\n layout.get('text-allow-overlap'),\n scale,\n textPixelRatio,\n placedSymbol,\n bucket.lineVertexArray,\n bucket.glyphOffsetArray,\n fontSize,\n posMatrix,\n textLabelPlaneMatrix,\n showCollisionBoxes,\n pitchWithMap,\n collisionGroup.predicate);\n // If text-allow-overlap is set, 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 = layout.get('text-allow-overlap') || placedGlyphCircles.circles.length > 0;\n offscreen = offscreen && placedGlyphCircles.offscreen;\n }\n\n if (collisionArrays.iconFeatureIndex) {\n iconFeatureIndex = collisionArrays.iconFeatureIndex;\n }\n if (collisionArrays.iconBox) {\n placedIconBoxes = this.collisionIndex.placeCollisionBox(collisionArrays.iconBox,\n layout.get('icon-allow-overlap'), textPixelRatio, posMatrix, collisionGroup.predicate);\n placeIcon = placedIconBoxes.box.length > 0;\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 if (placeText && placedGlyphBoxes && placedGlyphBoxes.box) {\n if (placedVertical && placedVertical.box && verticalTextFeatureIndex) {\n this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'),\n bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID);\n } else {\n this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'),\n bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);\n }\n\n }\n if (placeIcon && placedIconBoxes) {\n this.collisionIndex.insertCollisionBox(placedIconBoxes.box, layout.get('icon-ignore-placement'),\n bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID);\n }\n if (placeText && placedGlyphCircles) {\n this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, layout.get('text-ignore-placement'),\n bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);\n }\n\n assert(symbolInstance.crossTileID !== 0);\n assert(bucket.bucketInstanceId !== 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 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]);\n }\n } else {\n for (let i = 0; i < bucket.symbolInstances.length; ++i) {\n placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i]);\n }\n }\n\n bucket.justReloaded = false;\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\n const prevPlacement = this.prevPlacement;\n let placementChanged = false;\n\n const increment = (prevPlacement && this.fadeDuration !== 0) ?\n (this.commitTime - prevPlacement.commitTime) / this.fadeDuration :\n 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 assert(!prevPlacement || prevPlacement.lastPlacementChangeTime !== undefined);\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): any): SymbolBucket);\n if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) {\n this.updateBucketOpacities(symbolBucket, seenCrossTileIDs, tile.collisionBoxArray);\n }\n }\n }\n\n updateBucketOpacities(bucket: SymbolBucket, seenCrossTileIDs: { [string | number]: boolean }, collisionBoxArray: ?CollisionBoxArray) {\n if (bucket.hasTextData()) bucket.text.opacityVertexArray.clear();\n if (bucket.hasIconData()) bucket.icon.opacityVertexArray.clear();\n if (bucket.hasCollisionBoxData()) bucket.collisionBox.collisionVertexArray.clear();\n if (bucket.hasCollisionCircleData()) bucket.collisionCircle.collisionVertexArray.clear();\n\n const layout = bucket.layers[0].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 variablePlacement = layout.get('text-variable-anchor');\n const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\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.hasCollisionBoxData() || bucket.hasCollisionCircleData())) {\n bucket.deserializeCollisionBoxes(collisionBoxArray);\n }\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 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 opacityEntryCount = (numHorizontalGlyphVertices + numVerticalGlyphVertices) / 4;\n for (let i = 0; i < opacityEntryCount; i++) {\n bucket.text.opacityVertexArray.emplaceBack(packedOpacity);\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() ? 1 : 0;\n const placedOrientation = this.placedOrientations[symbolInstance.crossTileID];\n const verticalHidden = (placedOrientation === WritingMode.horizontal || placedOrientation === WritingMode.horizontalOnly) ? 1 : 0;\n const horizontalHidden = placedOrientation === WritingMode.vertical ? 1 : 0;\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;\n }\n });\n\n if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {\n bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden;\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 for (let i = 0; i < symbolInstance.numIconVertices / 4; i++) {\n bucket.icon.opacityVertexArray.emplaceBack(packedOpacity);\n }\n bucket.icon.placedSymbolArray.get(s).hidden =\n (opacityState.icon.isHidden(): any);\n }\n\n if (bucket.hasCollisionBoxData() || bucket.hasCollisionCircleData()) {\n const collisionArrays = bucket.collisionArrays[s];\n if (collisionArrays) {\n if (collisionArrays.textBox) {\n let shift = new Point(0, 0);\n let used = true;\n if (variablePlacement) {\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 = calculateVariableLayoutOffset(variableOffset.anchor,\n variableOffset.width,\n variableOffset.height,\n variableOffset.radialOffset,\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 updateCollisionVertices(bucket.collisionBox.collisionVertexArray, opacityState.text.placed, !used, shift.x, shift.y);\n }\n\n if (collisionArrays.iconBox) {\n updateCollisionVertices(bucket.collisionBox.collisionVertexArray, opacityState.icon.placed, false);\n }\n\n const textCircles = collisionArrays.textCircles;\n if (textCircles && bucket.hasCollisionCircleData()) {\n for (let k = 0; k < textCircles.length; k += 5) {\n const notUsed = isDuplicate || textCircles[k + 4] === 0;\n updateCollisionVertices(bucket.collisionCircle.collisionVertexArray, opacityState.text.placed, notUsed);\n }\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.hasCollisionBoxData() && bucket.collisionBox.collisionVertexBuffer) {\n bucket.collisionBox.collisionVertexBuffer.updateData(bucket.collisionBox.collisionVertexArray);\n }\n if (bucket.hasCollisionCircleData() && bucket.collisionCircle.collisionVertexBuffer) {\n bucket.collisionCircle.collisionVertexBuffer.updateData(bucket.collisionCircle.collisionVertexArray);\n }\n\n assert(bucket.text.opacityVertexArray.length === bucket.text.layoutVertexArray.length / 4);\n assert(bucket.icon.opacityVertexArray.length === bucket.icon.layoutVertexArray.length / 4);\n }\n\n symbolFadeChange(now: number) {\n return this.fadeDuration === 0 ?\n 1 :\n (now - this.commitTime) / this.fadeDuration;\n }\n\n hasTransitions(now: number) {\n return this.stale ||\n now - this.lastPlacementChangeTime < this.fadeDuration;\n }\n\n stillRecent(now: number) {\n return this.commitTime + this.fadeDuration > now;\n }\n\n setStale() {\n this.stale = true;\n }\n}\n\nfunction updateCollisionVertices(collisionVertexArray: CollisionVertexArray, placed: boolean, notUsed: boolean, shiftX?: number, shiftY?: number) {\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);\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","// @flow\n\nimport 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 Tile from '../source/tile';\n\nclass LayerPlacement {\n _currentTileIndex: number;\n _tiles: Array;\n _seenCrossTileIDs: { [string | number]: boolean };\n\n constructor() {\n this._currentTileIndex = 0;\n this._seenCrossTileIDs = {};\n }\n\n continuePlacement(tiles: Array, placement: Placement, showCollisionBoxes: boolean, styleLayer: StyleLayer, shouldPausePlacement: () => boolean) {\n while (this._currentTileIndex < tiles.length) {\n const tile = tiles[this._currentTileIndex];\n placement.placeLayerTile(styleLayer, tile, showCollisionBoxes, this._seenCrossTileIDs);\n\n this._currentTileIndex++;\n if (shouldPausePlacement()) {\n return true;\n }\n }\n }\n}\n\nclass PauseablePlacement {\n placement: Placement;\n _done: boolean;\n _currentPlacementIndex: number;\n _forceFullPlacement: boolean;\n _showCollisionBoxes: boolean;\n _inProgressLayer: ?LayerPlacement;\n\n constructor(transform: Transform, order: Array,\n forceFullPlacement: boolean,\n showCollisionBoxes: boolean,\n fadeDuration: number,\n crossSourceCollisions: boolean,\n prevPlacement?: Placement) {\n\n this.placement = new Placement(transform, 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(): boolean {\n return this._done;\n }\n\n continuePlacement(order: Array, layers: {[string]: StyleLayer}, layerTiles: {[string]: Array}) {\n const startTime = browser.now();\n\n const shouldPausePlacement = () => {\n const elapsedTime = browser.now() - startTime;\n return this._forceFullPlacement ? false : elapsedTime > 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();\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\nexport default PauseablePlacement;\n","// @flow\n\nimport EXTENT from '../data/extent';\n\nimport { SymbolInstanceArray } from '../data/array_types';\n\nimport type { SymbolInstance } from '../data/array_types';\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\nclass TileLayerIndex {\n tileID: OverscaledTileID;\n indexedSymbolInstances: {[number]: Array<{\n crossTileID: number,\n coord: {\n x: number,\n y: number\n }\n }>};\n bucketInstanceId: number;\n\n constructor(tileID: OverscaledTileID, symbolInstances: SymbolInstanceArray, bucketInstanceId: number) {\n this.tileID = tileID;\n this.indexedSymbolInstances = {};\n this.bucketInstanceId = bucketInstanceId;\n\n for (let i = 0; i < symbolInstances.length; i++) {\n const symbolInstance = symbolInstances.get(i);\n const key = symbolInstance.key;\n if (!this.indexedSymbolInstances[key]) {\n this.indexedSymbolInstances[key] = [];\n }\n // This tile may have multiple symbol instances with the same key\n // Store each one along with its coordinates\n this.indexedSymbolInstances[key].push({\n crossTileID: symbolInstance.crossTileID,\n coord: this.getScaledCoordinates(symbolInstance, tileID)\n });\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) world-based (so after conversion the source tile is irrelevant)\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) {\n const zDifference = childTileID.canonical.z - this.tileID.canonical.z;\n const scale = roundingFactor / Math.pow(2, zDifference);\n return {\n x: Math.floor((childTileID.canonical.x * EXTENT + symbolInstance.anchorX) * scale),\n y: Math.floor((childTileID.canonical.y * EXTENT + symbolInstance.anchorY) * scale)\n };\n }\n\n findMatches(symbolInstances: SymbolInstanceArray, newTileID: OverscaledTileID, zoomCrossTileIDs: {[crossTileID: number]: boolean}) {\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 indexedInstances = this.indexedSymbolInstances[symbolInstance.key];\n if (!indexedInstances) {\n // No symbol with this key in this bucket\n continue;\n }\n\n const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID);\n\n for (const thisTileSymbol of indexedInstances) {\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.coord.x - scaledSymbolCoord.x) <= tolerance &&\n Math.abs(thisTileSymbol.coord.y - scaledSymbolCoord.y) <= tolerance &&\n !zoomCrossTileIDs[thisTileSymbol.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[thisTileSymbol.crossTileID] = true;\n symbolInstance.crossTileID = thisTileSymbol.crossTileID;\n break;\n }\n }\n }\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: {[zoom: string | number]: {[tileId: string | number]: TileLayerIndex}};\n usedCrossTileIDs: {[zoom: string | number]: {[crossTileID: number]: boolean}};\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 key in removedBucket.indexedSymbolInstances) {\n for (const symbolInstance of removedBucket.indexedSymbolInstances[(key: any)]) {\n delete this.usedCrossTileIDs[zoom][symbolInstance.crossTileID];\n }\n }\n }\n\n removeStaleBuckets(currentIDs: { [string | number]: boolean }) {\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\nclass 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): any): 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\nexport default CrossTileSymbolIndex;\n","// @flow\n\nimport assert from 'assert';\n\nimport { 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 LineAtlas from '../render/line_atlas';\nimport { pick, clone, extend, deepEqual, filterObject, mapObject } from '../util/util';\nimport { getJSON, getReferrer, makeRequest, ResourceType } from '../util/ajax';\nimport { isMapboxURL } from '../util/mapbox';\nimport browser from '../util/browser';\nimport Dispatcher from '../util/dispatcher';\nimport { validateStyle, emitValidationErrors as _emitValidationErrors } from './validate_style';\nimport {\n getType as getSourceType,\n setType as setSourceType,\n type SourceClass\n} from '../source/source';\nimport { queryRenderedFeatures, queryRenderedSymbols, querySourceFeatures } from '../source/query_features';\nimport SourceCache from '../source/source_cache';\nimport GeoJSONSource from '../source/geojson_source';\nimport styleSpec from '../style-spec/reference/latest';\nimport getWorkerPool from '../util/global_worker_pool';\nimport deref from '../style-spec/deref';\nimport diffStyles, {operations as diffOperations} from '../style-spec/diff';\nimport {\n registerForPluginAvailability,\n evented as rtlTextPluginEvented\n} from '../source/rtl_text_plugin';\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';\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<{message: string, identifier?: string}>) =>\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 {StyleGlyph} from './style_glyph';\nimport type {Callback} from '../types/callback';\nimport type EvaluationParameters from './evaluation_parameters';\nimport type {Placement} from '../symbol/placement';\nimport type {Cancelable} from '../types/cancelable';\nimport type {RequestParameters, ResponseCallback} from '../util/ajax';\nimport type {GeoJSON} from '@mapbox/geojson-types';\nimport type {\n LayerSpecification,\n FilterSpecification,\n StyleSpecification,\n LightSpecification,\n SourceSpecification\n} from '../style-spec/types';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer';\nimport type {Validator} from './validate_style';\n\nconst supportedDiffOperations = pick(diffOperations, [\n 'addLayer',\n 'removeLayer',\n 'setPaintProperty',\n 'setLayoutProperty',\n 'setFilter',\n 'addSource',\n 'removeSource',\n 'setLayerZoomRange',\n 'setLight',\n 'setTransition',\n 'setGeoJSONSourceData'\n // 'setGlyphs',\n // 'setSprite',\n]);\n\nconst ignoredDiffOperations = pick(diffOperations, [\n 'setCenter',\n 'setZoom',\n 'setBearing',\n 'setPitch'\n]);\n\nexport type StyleOptions = {\n validate?: boolean,\n localIdeographFontFamily?: string\n};\n\nexport type StyleSetterOptions = {\n validate?: boolean\n};\n/**\n * @private\n */\nclass 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\n _request: ?Cancelable;\n _spriteRequest: ?Cancelable;\n _layers: {[string]: StyleLayer};\n _order: Array;\n sourceCaches: {[string]: SourceCache};\n zoomHistory: ZoomHistory;\n _loaded: boolean;\n _rtlTextPluginCallback: Function;\n _changed: boolean;\n _updatedSources: {[string]: 'clear' | 'reload'};\n _updatedLayers: {[string]: true};\n _removedLayers: {[string]: StyleLayer};\n _updatedPaintProps: {[layer: string]: true};\n _layerOrderChanged: boolean;\n\n crossTileSymbolIndex: CrossTileSymbolIndex;\n pauseablePlacement: PauseablePlacement;\n placement: Placement;\n z: number;\n\n // exposed to allow stubbing by unit tests\n static getSourceType: typeof getSourceType;\n static setSourceType: typeof setSourceType;\n static registerForPluginAvailability: typeof registerForPluginAvailability;\n\n constructor(map: Map, options: StyleOptions = {}) {\n super();\n\n this.map = map;\n this.dispatcher = new Dispatcher(getWorkerPool(), this);\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._layers = {};\n this._order = [];\n this.sourceCaches = {};\n this.zoomHistory = new ZoomHistory();\n this._loaded = false;\n\n this._resetUpdates();\n\n this.dispatcher.broadcast('setReferrer', getReferrer());\n\n const self = this;\n this._rtlTextPluginCallback = Style.registerForPluginAvailability((args) => {\n self.dispatcher.broadcast('loadRTLTextPlugin', args.pluginURL, args.completionCallback);\n for (const id in self.sourceCaches) {\n self.sourceCaches[id].reload(); // Should be a no-op if the plugin loads before any tiles load\n }\n });\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 loadURL(url: string, options: {\n validate?: boolean,\n accessToken?: string\n } = {}) {\n this.fire(new Event('dataloading', {dataType: 'style'}));\n\n const validate = typeof options.validate === 'boolean' ?\n options.validate : !isMapboxURL(url);\n\n url = this.map._requestManager.normalizeStyleURL(url, options.accessToken);\n const request = this.map._requestManager.transformRequest(url, ResourceType.Style);\n this._request = getJSON(request, (error: ?Error, json: ?Object) => {\n this._request = null;\n if (error) {\n this.fire(new ErrorEvent(error));\n } else if (json) {\n this._load(json, validate);\n }\n });\n }\n\n loadJSON(json: StyleSpecification, options: StyleSetterOptions = {}) {\n this.fire(new Event('dataloading', {dataType: 'style'}));\n\n this._request = browser.frame(() => {\n this._request = null;\n this._load(json, options.validate !== false);\n });\n }\n\n _load(json: StyleSpecification, validate: boolean) {\n if (validate && emitValidationErrors(this, validateStyle(json))) {\n return;\n }\n\n this._loaded = true;\n this.stylesheet = json;\n\n for (const id in json.sources) {\n this.addSource(id, json.sources[id], {validate: false});\n }\n\n if (json.sprite) {\n this._spriteRequest = loadSprite(json.sprite, this.map._requestManager, (err, images) => {\n this._spriteRequest = null;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (images) {\n for (const id in images) {\n this.imageManager.addImage(id, images[id]);\n }\n }\n\n this.imageManager.setLoaded(true);\n this.fire(new Event('data', {dataType: 'style'}));\n });\n } else {\n this.imageManager.setLoaded(true);\n }\n\n this.glyphManager.setURL(json.glyphs);\n\n const layers = deref(this.stylesheet.layers);\n\n this._order = layers.map((layer) => layer.id);\n\n this._layers = {};\n for (let layer of layers) {\n layer = createStyleLayer(layer);\n layer.setEventedParent(this, {layer: {id: layer.id}});\n this._layers[layer.id] = layer;\n }\n\n this.dispatcher.broadcast('setLayers', this._serializeLayers(this._order));\n\n this.light = new Light(this.stylesheet.light);\n\n this.fire(new Event('data', {dataType: 'style'}));\n this.fire(new Event('style.load'));\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 _serializeLayers(ids: Array): Array {\n const serializedLayers = [];\n for (const id of ids) {\n const layer = this._layers[id];\n if (layer.type !== 'custom') {\n serializedLayers.push(layer.serialize());\n }\n }\n return serializedLayers;\n }\n\n hasTransitions() {\n if (this.light && this.light.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 * 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 (this._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 assert(action === 'reload' || action === 'clear');\n if (action === 'reload') {\n this._reloadSource(id);\n } else if (action === 'clear') {\n this._clearSource(id);\n }\n }\n\n for (const id in this._updatedPaintProps) {\n this._layers[id].updateTransitions(parameters);\n }\n\n this.light.updateTransitions(parameters);\n\n this._resetUpdates();\n }\n\n for (const sourceId in this.sourceCaches) {\n this.sourceCaches[sourceId].used = false;\n }\n\n for (const layerId of this._order) {\n const layer = this._layers[layerId];\n\n layer.recalculate(parameters);\n if (!layer.isHidden(parameters.zoom) && layer.source) {\n this.sourceCaches[layer.source].used = true;\n }\n }\n\n this.light.recalculate(parameters);\n this.z = parameters.zoom;\n\n if (changed) {\n this.fire(new Event('data', {dataType: 'style'}));\n }\n\n }\n\n _updateWorkerLayers(updatedIds: Array, removedIds: Array) {\n this.dispatcher.broadcast('updateLayers', {\n layers: this._serializeLayers(updatedIds),\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\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 {boolean} true if any changes were made; false otherwise\n * @private\n */\n setState(nextState: StyleSpecification) {\n this._checkLoaded();\n\n if (emitValidationErrors(this, validateStyle(nextState))) return false;\n\n nextState = clone(nextState);\n nextState.layers = deref(nextState.layers);\n\n const changes = diffStyles(this.serialize(), nextState)\n .filter(op => !(op.command in ignoredDiffOperations));\n\n if (changes.length === 0) {\n return false;\n }\n\n const unimplementedOps = changes.filter(op => !(op.command in supportedDiffOperations));\n if (unimplementedOps.length > 0) {\n throw new Error(`Unimplemented: ${unimplementedOps.map(op => op.command).join(', ')}.`);\n }\n\n changes.forEach((op) => {\n if (op.command === 'setTransition') {\n // `transition` is always read directly off of\n // `this.stylesheet`, which we update below\n return;\n }\n (this: any)[op.command].apply(this, op.args);\n });\n\n this.stylesheet = nextState;\n\n return true;\n }\n\n addImage(id: string, image: StyleImage) {\n if (this.getImage(id)) {\n return this.fire(new ErrorEvent(new Error('An image with this name already exists.')));\n }\n this.imageManager.addImage(id, image);\n this.fire(new Event('data', {dataType: 'style'}));\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('No image with this name exists.')));\n }\n this.imageManager.removeImage(id);\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, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n if (this.sourceCaches[id] !== undefined) {\n throw new Error('There is already a source with this ID');\n }\n\n if (!source.type) {\n throw new Error(`The type property must be defined, but the 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\n if (this.map && this.map._collectResourceTiming) (source: 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: this.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 {string} id id of the source to remove\n * @throws {Error} if no source is found with the given ID\n */\n removeSource(id: string) {\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.clearTiles();\n\n if (sourceCache.onRemove) sourceCache.onRemove(this.map);\n this._changed = true;\n }\n\n /**\n * Set the data of a GeoJSON source, given its id.\n * @param {string} id id of the source\n * @param {GeoJSON|string} data GeoJSON source\n */\n setGeoJSONSourceData(id: string, data: GeoJSON | string) {\n this._checkLoaded();\n\n assert(this.sourceCaches[id] !== undefined, 'There is no source with this ID');\n const geojsonSource: GeoJSONSource = (this.sourceCaches[id].getSource(): any);\n assert(geojsonSource.type === 'geojson');\n\n geojsonSource.setData(data);\n this._changed = true;\n }\n\n /**\n * Get a source by id.\n * @param {string} id id of the desired source\n * @returns {Object} source\n */\n getSource(id: string): Object {\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 {string} [before] ID of an existing layer to insert before\n */\n addLayer(layerObject: LayerSpecification | CustomLayerInterface, before?: string, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const id = layerObject.id;\n\n if (this.getLayer(id)) {\n this.fire(new ErrorEvent(new Error(`Layer with id \"${id}\" already exists on this map`)));\n return;\n }\n\n let layer;\n if (layerObject.type === 'custom') {\n\n if (emitValidationErrors(this, validateCustomStyleLayer(layerObject))) return;\n\n layer = createStyleLayer(layerObject);\n\n } else {\n if (typeof layerObject.source === 'object') {\n this.addSource(id, layerObject.source);\n layerObject = clone(layerObject);\n layerObject = (extend(layerObject, {source: id}): any);\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);\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(`Layer with id \"${before}\" does not exist on this map.`)));\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 underyling 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 {string} id ID of the layer to move\n * @param {string} [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(`Layer with id \"${before}\" does not exist on this map.`)));\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 *\n * If no such layer exists, an `error` event is fired.\n *\n * @param {string} id id of the layer to remove\n * @fires error\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(`The layer '${id}' does not exist in the map's style and cannot be removed.`)));\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 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 {string} id - id of the desired layer\n * @returns {?Object} a layer, if one with the given `id` exists\n */\n getLayer(id: string): Object {\n return this._layers[id];\n }\n\n setLayerZoomRange(layerId: string, minzoom: ?number, maxzoom: ?number) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot have zoom extent.`)));\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, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be filtered.`)));\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 {string} layer the layer to inspect\n * @returns {*} the layer's filter, if any\n */\n getFilter(layer: string) {\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(`The layer '${layerId}' does not exist in the map's style and cannot be styled.`)));\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 {string} layerId the layer to inspect\n * @param {string} 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(`The layer '${layerId}' does not exist in the map's style.`)));\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(`The layer '${layerId}' does not exist in the map's style and cannot be styled.`)));\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 }\n\n getPaintProperty(layer: string, name: string) {\n return this.getLayer(layer).getPaintProperty(name);\n }\n\n setFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }, state: Object) {\n this._checkLoaded();\n const sourceId = feature.source;\n const sourceLayer = feature.sourceLayer;\n const sourceCache = this.sourceCaches[sourceId];\n const featureId = parseInt(feature.id, 10);\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 (isNaN(featureId) || featureId < 0) {\n this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided and non-negative.`)));\n return;\n }\n\n sourceCache.setFeatureState(sourceLayer, featureId, state);\n }\n\n removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, 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 const featureId = parseInt(target.id, 10);\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 (target.id !== undefined && isNaN(featureId) || featureId < 0) {\n this.fire(new ErrorEvent(new Error(`The feature id parameter must be non-negative.`)));\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 requred to remove its specific state property.`)));\n return;\n }\n\n sourceCache.removeFeatureState(sourceLayer, featureId, key);\n }\n\n getFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }) {\n this._checkLoaded();\n const sourceId = feature.source;\n const sourceLayer = feature.sourceLayer;\n const sourceCache = this.sourceCaches[sourceId];\n const featureId = parseInt(feature.id, 10);\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 (isNaN(featureId) || featureId < 0) {\n this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided and non-negative.`)));\n return;\n }\n\n return sourceCache.getFeatureState(sourceLayer, featureId);\n }\n\n getTransition() {\n return extend({ duration: 300, delay: 0 }, this.stylesheet && this.stylesheet.transition);\n }\n\n serialize() {\n return filterObject({\n version: this.stylesheet.version,\n name: this.stylesheet.name,\n metadata: this.stylesheet.metadata,\n light: this.stylesheet.light,\n center: this.stylesheet.center,\n zoom: this.stylesheet.zoom,\n bearing: this.stylesheet.bearing,\n pitch: this.stylesheet.pitch,\n sprite: this.stylesheet.sprite,\n glyphs: this.stylesheet.glyphs,\n transition: this.stylesheet.transition,\n sources: mapObject(this.sourceCaches, (source) => source.serialize()),\n layers: this._serializeLayers(this._order)\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 this._updatedSources[layer.source] = 'reload';\n this.sourceCaches[layer.source].pause();\n }\n this._changed = true;\n }\n\n _flattenAndSortRenderedFeatures(sourceResults: Array) {\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: any, 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 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 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 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(sourceID: string, params: ?{sourceLayer: ?string, filter: ?Array, validate?: boolean}) {\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 addSourceType(name: string, SourceType: SourceClass, callback: Callback) {\n if (Style.getSourceType(name)) {\n return callback(new Error(`A source type called \"${name}\" already exists.`));\n }\n\n Style.setSourceType(name, SourceType);\n\n if (!SourceType.workerSourceURL) {\n return callback(null, null);\n }\n\n this.dispatcher.broadcast('loadWorkerSource', {\n name,\n url: SourceType.workerSourceURL\n }, callback);\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 _validate(validate: Validator, key: string, value: any, props: any, options: { validate?: boolean } = {}) {\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() {\n if (this._request) {\n this._request.cancel();\n this._request = null;\n }\n if (this._spriteRequest) {\n this._spriteRequest.cancel();\n this._spriteRequest = null;\n }\n rtlTextPluginEvented.off('pluginAvailable', this._rtlTextPluginCallback);\n for (const id in this.sourceCaches) {\n this.sourceCaches[id].clearTiles();\n }\n this.dispatcher.remove();\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);\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) {\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 const forceFullPlacement = this._layerOrderChanged || fadeDuration === 0;\n\n if (forceFullPlacement || !this.pauseablePlacement || (this.pauseablePlacement.isDone() && !this.placement.stillRecent(browser.now()))) {\n this.pauseablePlacement = new PauseablePlacement(transform, 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 getImages(mapId: string, params: {icons: Array}, callback: Callback<{[string]: StyleImage}>) {\n this.imageManager.getImages(params.icons, callback);\n }\n\n getGlyphs(mapId: string, params: {stacks: {[string]: Array}}, callback: Callback<{[string]: {[number]: ?StyleGlyph}}>) {\n this.glyphManager.getGlyphs(params.stacks, callback);\n }\n\n getResource(mapId: string, params: RequestParameters, callback: ResponseCallback): Cancelable {\n return makeRequest(params, callback);\n }\n}\n\nStyle.getSourceType = getSourceType;\nStyle.setSourceType = setSourceType;\nStyle.registerForPluginAvailability = registerForPluginAvailability;\n\nexport default Style;\n","// @flow\n\nimport { getJSON, getImage, ResourceType } from '../util/ajax';\n\nimport browser from '../util/browser';\nimport { RGBAImage } from '../util/image';\n\nimport type {StyleImage} from './style_image';\nimport type {RequestManager} from '../util/mapbox';\nimport type {Callback} from '../types/callback';\nimport type {Cancelable} from '../types/cancelable';\n\nexport default function(baseURL: string,\n requestManager: RequestManager,\n callback: Callback<{[string]: StyleImage}>): Cancelable {\n let json: any, image, error;\n const format = browser.devicePixelRatio > 1 ? '@2x' : '';\n\n let jsonRequest = getJSON(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.json'), ResourceType.SpriteJSON), (err: ?Error, data: ?Object) => {\n jsonRequest = null;\n if (!error) {\n error = err;\n json = data;\n maybeComplete();\n }\n });\n\n let imageRequest = getImage(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.png'), ResourceType.SpriteImage), (err, img) => {\n imageRequest = null;\n if (!error) {\n error = err;\n image = img;\n maybeComplete();\n }\n });\n\n function maybeComplete() {\n if (error) {\n callback(error);\n } else if (json && image) {\n const imageData = browser.getImageData(image);\n const result = {};\n\n for (const id in json) {\n const {width, height, x, y, sdf, pixelRatio} = json[id];\n const data = new RGBAImage({width, height});\n RGBAImage.copy(imageData, data, {x, y}, {x: 0, y: 0}, {width, height});\n result[id] = {data, pixelRatio, sdf};\n }\n\n callback(null, result);\n }\n }\n\n return {\n cancel() {\n if (jsonRequest) {\n jsonRequest.cancel();\n jsonRequest = null;\n }\n if (imageRequest) {\n imageRequest.cancel();\n imageRequest = null;\n }\n }\n };\n}\n","// @flow\nimport { 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/* eslint-disable flowtype/require-valid-file-annotation */\n\nimport preludeFrag from './_prelude.fragment.glsl';\nimport preludeVert from './_prelude.vertex.glsl';\nimport backgroundFrag from './background.fragment.glsl';\nimport backgroundVert from './background.vertex.glsl';\nimport backgroundPatternFrag from './background_pattern.fragment.glsl';\nimport backgroundPatternVert from './background_pattern.vertex.glsl';\nimport circleFrag from './circle.fragment.glsl';\nimport circleVert from './circle.vertex.glsl';\nimport clippingMaskFrag from './clipping_mask.fragment.glsl';\nimport clippingMaskVert from './clipping_mask.vertex.glsl';\nimport heatmapFrag from './heatmap.fragment.glsl';\nimport heatmapVert from './heatmap.vertex.glsl';\nimport heatmapTextureFrag from './heatmap_texture.fragment.glsl';\nimport heatmapTextureVert from './heatmap_texture.vertex.glsl';\nimport collisionBoxFrag from './collision_box.fragment.glsl';\nimport collisionBoxVert from './collision_box.vertex.glsl';\nimport collisionCircleFrag from './collision_circle.fragment.glsl';\nimport collisionCircleVert from './collision_circle.vertex.glsl';\nimport debugFrag from './debug.fragment.glsl';\nimport debugVert from './debug.vertex.glsl';\nimport fillFrag from './fill.fragment.glsl';\nimport fillVert from './fill.vertex.glsl';\nimport fillOutlineFrag from './fill_outline.fragment.glsl';\nimport fillOutlineVert from './fill_outline.vertex.glsl';\nimport fillOutlinePatternFrag from './fill_outline_pattern.fragment.glsl';\nimport fillOutlinePatternVert from './fill_outline_pattern.vertex.glsl';\nimport fillPatternFrag from './fill_pattern.fragment.glsl';\nimport fillPatternVert from './fill_pattern.vertex.glsl';\nimport fillExtrusionFrag from './fill_extrusion.fragment.glsl';\nimport fillExtrusionVert from './fill_extrusion.vertex.glsl';\nimport fillExtrusionPatternFrag from './fill_extrusion_pattern.fragment.glsl';\nimport fillExtrusionPatternVert from './fill_extrusion_pattern.vertex.glsl';\nimport hillshadePrepareFrag from './hillshade_prepare.fragment.glsl';\nimport hillshadePrepareVert from './hillshade_prepare.vertex.glsl';\nimport hillshadeFrag from './hillshade.fragment.glsl';\nimport hillshadeVert from './hillshade.vertex.glsl';\nimport lineFrag from './line.fragment.glsl';\nimport lineVert from './line.vertex.glsl';\nimport lineGradientFrag from './line_gradient.fragment.glsl';\nimport lineGradientVert from './line_gradient.vertex.glsl';\nimport linePatternFrag from './line_pattern.fragment.glsl';\nimport linePatternVert from './line_pattern.vertex.glsl';\nimport lineSDFFrag from './line_sdf.fragment.glsl';\nimport lineSDFVert from './line_sdf.vertex.glsl';\nimport rasterFrag from './raster.fragment.glsl';\nimport rasterVert from './raster.vertex.glsl';\nimport symbolIconFrag from './symbol_icon.fragment.glsl';\nimport symbolIconVert from './symbol_icon.vertex.glsl';\nimport symbolSDFFrag from './symbol_sdf.fragment.glsl';\nimport symbolSDFVert from './symbol_sdf.vertex.glsl';\n\nexport const prelude = compile(preludeFrag, preludeVert);\nexport const background = compile(backgroundFrag, backgroundVert);\nexport const backgroundPattern = compile(backgroundPatternFrag, backgroundPatternVert);\nexport const circle = compile(circleFrag, circleVert);\nexport const clippingMask = compile(clippingMaskFrag, clippingMaskVert);\nexport const heatmap = compile(heatmapFrag, heatmapVert);\nexport const heatmapTexture = compile(heatmapTextureFrag, heatmapTextureVert);\nexport const collisionBox = compile(collisionBoxFrag, collisionBoxVert);\nexport const collisionCircle = compile(collisionCircleFrag, collisionCircleVert);\nexport const debug = compile(debugFrag, debugVert);\nexport const fill = compile(fillFrag, fillVert);\nexport const fillOutline = compile(fillOutlineFrag, fillOutlineVert);\nexport const fillOutlinePattern = compile(fillOutlinePatternFrag, fillOutlinePatternVert);\nexport const fillPattern = compile(fillPatternFrag, fillPatternVert);\nexport const fillExtrusion = compile(fillExtrusionFrag, fillExtrusionVert);\nexport const fillExtrusionPattern = compile(fillExtrusionPatternFrag, fillExtrusionPatternVert);\nexport const hillshadePrepare = compile(hillshadePrepareFrag, hillshadePrepareVert);\nexport const hillshade = compile(hillshadeFrag, hillshadeVert);\nexport const line = compile(lineFrag, lineVert);\nexport const lineGradient = compile(lineGradientFrag, lineGradientVert);\nexport const linePattern = compile(linePatternFrag, linePatternVert);\nexport const lineSDF = compile(lineSDFFrag, lineSDFVert);\nexport const raster = compile(rasterFrag, rasterVert);\nexport const symbolIcon = compile(symbolIconFrag, symbolIconVert);\nexport const symbolSDF = compile(symbolSDFFrag, symbolSDFVert);\n\n// Expand #pragmas to #ifdefs.\n\nfunction compile(fragmentSource, vertexSource) {\n const re = /#pragma mapbox: ([\\w]+) ([\\w]+) ([\\w]+) ([\\w]+)/g;\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};\n}\n","// @flow\n\nimport assert from 'assert';\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\nclass 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 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,\n vertexOffset: ?number,\n dynamicVertexBuffer: ?VertexBuffer,\n dynamicVertexBuffer2: ?VertexBuffer) {\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 );\n\n if (!context.extVertexArrayObject || isFreshBindRequired) {\n this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2);\n } else {\n context.bindVertexArrayOES.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 }\n\n freshBind(program: Program<*>,\n layoutVertexBuffer: VertexBuffer,\n paintVertexBuffers: Array,\n indexBuffer: ?IndexBuffer,\n vertexOffset: ?number,\n dynamicVertexBuffer: ?VertexBuffer,\n dynamicVertexBuffer2: ?VertexBuffer) {\n let numPrevAttributes;\n const numNextAttributes = program.numAttributes;\n\n const context = this.context;\n const gl = context.gl;\n\n if (context.extVertexArrayObject) {\n if (this.vao) this.destroy();\n this.vao = context.extVertexArrayObject.createVertexArrayOES();\n context.bindVertexArrayOES.set(this.vao);\n numPrevAttributes = 0;\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\n } else {\n numPrevAttributes = context.currentNumAttributes || 0;\n\n // Disable all attributes from the previous program that aren't used in\n // the new program. Note: attribute indices are *not* program specific!\n for (let i = numNextAttributes; i < numPrevAttributes; i++) {\n // WebGL breaks if you disable attribute 0.\n // http://stackoverflow.com/questions/20305231\n assert(i !== 0);\n gl.disableVertexAttribArray(i);\n }\n }\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\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\n context.currentNumAttributes = numNextAttributes;\n }\n\n destroy() {\n if (this.vao) {\n this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao);\n this.vao = null;\n }\n }\n}\n\nexport default VertexArrayObject;\n","// @flow\n\nimport {prelude} from '../shaders';\nimport assert from 'assert';\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';\n\nexport type DrawMode =\n | $PropertyType\n | $PropertyType\n | $PropertyType;\n\nclass Program {\n program: WebGLProgram;\n attributes: {[string]: number};\n numAttributes: number;\n fixedUniforms: Us;\n binderUniforms: Array;\n\n constructor(context: Context,\n source: {fragmentSource: string, vertexSource: string},\n configuration: ProgramConfiguration,\n fixedUniforms: (Context, UniformLocations) => Us,\n showOverdrawInspector: boolean) {\n const gl = context.gl;\n this.program = gl.createProgram();\n\n const defines = configuration.defines();\n if (showOverdrawInspector) {\n defines.push('#define OVERDRAW_INSPECTOR;');\n }\n\n const fragmentSource = defines.concat(prelude.fragmentSource, source.fragmentSource).join('\\n');\n const vertexSource = defines.concat(prelude.vertexSource, source.vertexSource).join('\\n');\n const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragmentShader, fragmentSource);\n gl.compileShader(fragmentShader);\n assert(gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS), (gl.getShaderInfoLog(fragmentShader): any));\n gl.attachShader(this.program, fragmentShader);\n\n const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertexShader, vertexSource);\n gl.compileShader(vertexShader);\n assert(gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS), (gl.getShaderInfoLog(vertexShader): any));\n gl.attachShader(this.program, vertexShader);\n\n // Manually bind layout attributes in the order defined by their\n // ProgramInterface so that we don't dynamically link an unused\n // attribute at position 0, which can cause rendering to fail for an\n // entire layer (see #4607, #4728)\n const layoutAttributes = configuration.layoutAttributes || [];\n for (let i = 0; i < layoutAttributes.length; i++) {\n gl.bindAttribLocation(this.program, i, layoutAttributes[i].name);\n }\n\n gl.linkProgram(this.program);\n assert(gl.getProgramParameter(this.program, gl.LINK_STATUS), (gl.getProgramInfoLog(this.program): any));\n\n this.numAttributes = gl.getProgramParameter(this.program, gl.ACTIVE_ATTRIBUTES);\n\n this.attributes = {};\n const uniformLocations = {};\n\n for (let i = 0; i < this.numAttributes; i++) {\n const attribute = gl.getActiveAttrib(this.program, i);\n if (attribute) {\n this.attributes[attribute.name] = gl.getAttribLocation(this.program, attribute.name);\n }\n }\n\n const numUniforms = gl.getProgramParameter(this.program, gl.ACTIVE_UNIFORMS);\n for (let i = 0; i < numUniforms; i++) {\n const uniform = gl.getActiveUniform(this.program, i);\n if (uniform) {\n uniformLocations[uniform.name] = gl.getUniformLocation(this.program, uniform.name);\n }\n }\n\n this.fixedUniforms = fixedUniforms(context, uniformLocations);\n this.binderUniforms = 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 layerID: string,\n layoutVertexBuffer: VertexBuffer,\n indexBuffer: IndexBuffer,\n segments: SegmentVector,\n currentProperties: any,\n zoom: ?number,\n configuration: ?ProgramConfiguration,\n dynamicLayoutBuffer: ?VertexBuffer,\n dynamicLayoutBuffer2: ?VertexBuffer) {\n\n const gl = context.gl;\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 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: any)});\n }\n\n const primitiveSize = {\n [gl.LINES]: 2,\n [gl.TRIANGLES]: 3,\n [gl.LINE_STRIP]: 1\n }[drawMode];\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 );\n\n gl.drawElements(\n drawMode,\n segment.primitiveLength * primitiveSize,\n gl.UNSIGNED_SHORT,\n segment.primitiveOffset * primitiveSize * 2);\n }\n }\n}\n\nexport default Program;\n","// @flow\n\nimport assert from 'assert';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform4f\n} from '../uniform_binding';\nimport pixelsToTileUnits from '../../source/pixels_to_tile_units';\nimport browser from '../../util/browser';\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';\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': Uniform4f,\n 'u_fade': Uniform1f,\n 'u_pixel_coord_upper': Uniform2f,\n 'u_pixel_coord_lower': Uniform2f\n|};\n\nfunction patternUniformValues(crossfade: CrossfadeParameters, painter: Painter,\n tile: Tile\n): 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 // this assumes all images in the icon atlas texture have the same pixel ratio\n 'u_scale': [browser.devicePixelRatio, 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(image: CrossFaded, crossfade: CrossfadeParameters, painter: Painter,\n tile: {tileID: OverscaledTileID, tileSize: number}\n): UniformValues {\n const imagePosA = painter.imageManager.getPattern(image.from);\n const imagePosB = painter.imageManager.getPattern(image.to);\n assert(imagePosA && imagePosB);\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: any).tl,\n 'u_pattern_br_a': (imagePosA: any).br,\n 'u_pattern_tl_b': (imagePosB: any).tl,\n 'u_pattern_br_b': (imagePosB: any).br,\n 'u_texsize': [width, height],\n 'u_mix': crossfade.t,\n 'u_pattern_size_a': (imagePosA: any).displaySize,\n 'u_pattern_size_b': (imagePosB: 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","// @flow\n\nimport { patternUniformValues } from './pattern';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n Uniform4f,\n UniformMatrix4f\n} from '../uniform_binding';\n\nimport {mat3, 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': Uniform4f,\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 Uniform4f(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: Float32Array,\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];\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: Float32Array,\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/**\r\n * 3x3 Matrix\r\n * @module mat3\r\n */\n\n/**\r\n * Creates a new identity mat3\r\n *\r\n * @returns {mat3} a new 3x3 matrix\r\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/**\r\n * Copies the upper-left 3x3 values into the given mat3.\r\n *\r\n * @param {mat3} out the receiving 3x3 matrix\r\n * @param {mat4} a the source 4x4 matrix\r\n * @returns {mat3} out\r\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/**\r\n * Creates a new mat3 initialized with values from an existing matrix\r\n *\r\n * @param {mat3} a matrix to clone\r\n * @returns {mat3} a new 3x3 matrix\r\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/**\r\n * Copy the values from one mat3 to another\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\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/**\r\n * Create a new mat3 with the given values\r\n *\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\r\n * @returns {mat3} A new mat3\r\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/**\r\n * Set the components of a mat3 to the given values\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\r\n * @returns {mat3} out\r\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/**\r\n * Set a mat3 to the identity matrix\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @returns {mat3} out\r\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/**\r\n * Transpose the values of a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\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/**\r\n * Inverts a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\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/**\r\n * Calculates the adjugate of a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\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/**\r\n * Calculates the determinant of a mat3\r\n *\r\n * @param {mat3} a the source matrix\r\n * @returns {Number} determinant of a\r\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/**\r\n * Multiplies two mat3's\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @returns {mat3} out\r\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/**\r\n * Translate a mat3 by the given vector\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to translate\r\n * @param {vec2} v vector to translate by\r\n * @returns {mat3} out\r\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/**\r\n * Rotates a mat3 by the given angle\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat3} out\r\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/**\r\n * Scales the mat3 by the dimensions in the given vec2\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to rotate\r\n * @param {vec2} v the vec2 to scale the matrix by\r\n * @returns {mat3} out\r\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/**\r\n * Creates a matrix from a vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.translate(dest, dest, vec);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {vec2} v Translation vector\r\n * @returns {mat3} out\r\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/**\r\n * Creates a matrix from a given angle\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.rotate(dest, dest, rad);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat3} out\r\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/**\r\n * Creates a matrix from a vector scaling\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.scale(dest, dest, vec);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {vec2} v Scaling vector\r\n * @returns {mat3} out\r\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/**\r\n * Copies the values from a mat2d into a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat2d} a the matrix to copy\r\n * @returns {mat3} out\r\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/**\r\n* Calculates a 3x3 matrix from the given quaternion\r\n*\r\n* @param {mat3} out mat3 receiving operation result\r\n* @param {quat} q Quaternion to create matrix from\r\n*\r\n* @returns {mat3} out\r\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/**\r\n* Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\r\n*\r\n* @param {mat3} out mat3 receiving operation result\r\n* @param {mat4} a Mat4 to derive the normal matrix from\r\n*\r\n* @returns {mat3} out\r\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/**\r\n * Generates a 2D projection matrix with the given bounds\r\n *\r\n * @param {mat3} out mat3 frustum matrix will be written into\r\n * @param {number} width Width of your gl context\r\n * @param {number} height Height of gl context\r\n * @returns {mat3} out\r\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/**\r\n * Returns a string representation of a mat3\r\n *\r\n * @param {mat3} a matrix to represent as a string\r\n * @returns {String} string representation of the matrix\r\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/**\r\n * Returns Frobenius norm of a mat3\r\n *\r\n * @param {mat3} a the matrix to calculate Frobenius norm of\r\n * @returns {Number} Frobenius norm\r\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/**\r\n * Adds two mat3's\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @returns {mat3} out\r\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/**\r\n * Subtracts matrix b from matrix a\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @returns {mat3} out\r\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/**\r\n * Multiply each element of the matrix by a scalar.\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to scale\r\n * @param {Number} b amount to scale the matrix's elements by\r\n * @returns {mat3} out\r\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/**\r\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\r\n *\r\n * @param {mat3} out the receiving vector\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @param {Number} scale the amount to scale b's elements by before adding\r\n * @returns {mat3} out\r\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/**\r\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {mat3} a The first matrix.\r\n * @param {mat3} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\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/**\r\n * Returns whether or not the matrices have approximately the same elements in the same position.\r\n *\r\n * @param {mat3} a The first matrix.\r\n * @param {mat3} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\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/**\r\n * Alias for {@link mat3.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link mat3.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;","// @flow\n\nimport {patternUniformValues} from './pattern';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform4f,\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';\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': Uniform4f,\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': Uniform4f,\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 Uniform4f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade)\n\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 Uniform4f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade)\n});\n\nconst fillUniformValues = (matrix: Float32Array): UniformValues => ({\n 'u_matrix': matrix\n});\n\nconst fillPatternUniformValues = (\n matrix: Float32Array,\n painter: Painter,\n crossfade: CrossfadeParameters,\n tile: Tile\n): UniformValues => extend(\n fillUniformValues(matrix),\n patternUniformValues(crossfade, painter, tile)\n);\n\nconst fillOutlineUniformValues = (\n matrix: Float32Array,\n drawingBufferSize: [number, number]\n): UniformValues => ({\n 'u_matrix': matrix,\n 'u_world': drawingBufferSize\n});\n\nconst fillOutlinePatternUniformValues = (\n matrix: Float32Array,\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","// @flow\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 {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';\nimport browser from '../../util/browser';\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': browser.devicePixelRatio,\n 'u_extrude_scale': extrudeScale\n };\n};\n\nexport { circleUniforms, circleUniformValues };\n","// @flow\n\nimport {\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 {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Transform from '../../geo/transform';\nimport type Tile from '../../source/tile';\n\nexport type CollisionUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_camera_to_center_distance': Uniform1f,\n 'u_pixels_to_tile_units': Uniform1f,\n 'u_extrude_scale': Uniform2f,\n 'u_overscale_factor': Uniform1f\n|};\n\nconst collisionUniforms = (context: Context, locations: UniformLocations): CollisionUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_pixels_to_tile_units': new Uniform1f(context, locations.u_pixels_to_tile_units),\n 'u_extrude_scale': new Uniform2f(context, locations.u_extrude_scale),\n 'u_overscale_factor': new Uniform1f(context, locations.u_overscale_factor)\n});\n\nconst collisionUniformValues = (\n matrix: Float32Array,\n transform: Transform,\n tile: Tile\n): UniformValues => {\n const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom);\n const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);\n const overscaleFactor = tile.tileID.overscaleFactor();\n return {\n 'u_matrix': matrix,\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\n 'u_pixels_to_tile_units': pixelRatio,\n 'u_extrude_scale': [transform.pixelsToGLUnits[0] / (pixelRatio * scale),\n transform.pixelsToGLUnits[1] / (pixelRatio * scale)],\n 'u_overscale_factor': overscaleFactor\n };\n};\n\nexport { collisionUniforms, collisionUniformValues };\n","// @flow\n\nimport {\n UniformColor,\n UniformMatrix4f\n} from '../uniform_binding';\n\nimport type Context from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Color from '../../style-spec/util/color';\n\nexport type DebugUniformsType = {|\n 'u_color': UniformColor,\n 'u_matrix': UniformMatrix4f\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});\n\nconst debugUniformValues = (matrix: Float32Array, color: Color): UniformValues => ({\n 'u_matrix': matrix,\n 'u_color': color\n});\n\nexport { debugUniforms, debugUniformValues };\n","// @flow\n\nimport { UniformMatrix4f } from '../uniform_binding';\n\nimport type Context from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\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: Float32Array): UniformValues => ({\n 'u_matrix': matrix\n});\n\nexport { clippingMaskUniforms, clippingMaskUniformValues };\n","// @flow\n\nimport { 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 = (\n matrix: Float32Array,\n tile: Tile,\n zoom: number,\n intensity: number\n): 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","// @flow\n\nimport assert from 'assert';\nimport { mat4 } from 'gl-matrix';\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformColor,\n UniformMatrix4f\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_maxzoom': Uniform1f\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_maxzoom': new Uniform1f(context, locations.u_maxzoom)\n});\n\nconst hillshadeUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: HillshadeStyleLayer\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': 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 = (\n tile: {dem: ?DEMData, tileID: OverscaledTileID}, maxzoom: number\n): UniformValues => {\n assert(tile.dem);\n const stride = ((tile.dem: any): DEMData).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': tile.tileID.overscaledZ,\n 'u_maxzoom': maxzoom\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","// @flow\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform4f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport pixelsToTileUnits from '../../source/pixels_to_tile_units';\nimport { extend } from '../../util/util';\nimport browser from '../../util/browser';\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';\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|};\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': Uniform4f,\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});\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 Uniform4f(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): UniformValues => {\n const transform = painter.transform;\n\n return {\n 'u_matrix': calculateMatrix(painter, tile, layer),\n 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom),\n 'u_device_pixel_ratio': browser.devicePixelRatio,\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): UniformValues => {\n return extend(lineUniformValues(painter, tile, layer), {\n 'u_image': 0\n });\n};\n\nconst linePatternUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: LineStyleLayer,\n crossfade: CrossfadeParameters\n): UniformValues => {\n const transform = painter.transform;\n const tileZoomRatio = calculateTileRatio(tile, transform);\n return {\n 'u_matrix': calculateMatrix(painter, tile, layer),\n 'u_texsize': tile.imageAtlasTexture.size,\n // camera zoom ratio\n 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom),\n 'u_device_pixel_ratio': browser.devicePixelRatio,\n 'u_image': 0,\n // this assumes all images in the icon atlas texture have the same pixel ratio\n 'u_scale': [browser.devicePixelRatio, 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): 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), {\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 * browser.devicePixelRatio) / 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, tile, layer) {\n return painter.translatePosMatrix(\n 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","// @flow\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n UniformMatrix4f\n} 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';\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: Float32Array,\n parentTL: [number, number],\n parentScaleBy: number,\n fade: {mix: number, opacity: number},\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","// @flow\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport { extend } from '../../util/util';\nimport browser from '../../util/browser';\n\nimport type Context from '../../gl/context';\nimport type Painter from '../painter';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\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': Uniform1f,\n 'u_pitch_with_map': Uniform1i,\n 'u_texsize': Uniform2f,\n 'u_texture': Uniform1i\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': Uniform1f,\n 'u_pitch_with_map': Uniform1i,\n 'u_texsize': Uniform2f,\n 'u_texture': Uniform1i,\n 'u_gamma_scale': Uniform1f,\n 'u_device_pixel_ratio': Uniform1f,\n 'u_is_halo': 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 Uniform1f(context, locations.u_is_text),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_texture': new Uniform1i(context, locations.u_texture)\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 Uniform1f(context, locations.u_is_text),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\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 Uniform1f(context, locations.u_is_halo)\n});\n\nconst symbolIconUniformValues = (\n functionType: string,\n size: ?{uSizeT: number, uSize: number},\n rotateInShader: boolean,\n pitchWithMap: boolean,\n painter: Painter,\n matrix: Float32Array,\n labelPlaneMatrix: Float32Array,\n glCoordMatrix: Float32Array,\n isText: boolean,\n texSize: [number, 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_texsize': texSize,\n 'u_texture': 0\n };\n};\n\nconst symbolSDFUniformValues = (\n functionType: string,\n size: ?{uSizeT: number, uSize: number},\n rotateInShader: boolean,\n pitchWithMap: boolean,\n painter: Painter,\n matrix: Float32Array,\n labelPlaneMatrix: Float32Array,\n glCoordMatrix: Float32Array,\n isText: boolean,\n texSize: [number, number],\n isHalo: boolean\n): UniformValues => {\n const transform = painter.transform;\n\n return extend(symbolIconUniformValues(functionType, size,\n rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix,\n glCoordMatrix, isText, texSize), {\n 'u_gamma_scale': (pitchWithMap ? Math.cos(transform._pitch) * transform.cameraToCenterDistance : 1),\n 'u_device_pixel_ratio': browser.devicePixelRatio,\n 'u_is_halo': +isHalo\n });\n};\n\nexport { symbolIconUniforms, symbolSDFUniforms, symbolIconUniformValues, symbolSDFUniformValues };\n","// @flow\n\nimport { 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 from '../../style-spec/util/color';\nimport type {CrossFaded} from '../../style/properties';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport type {OverscaledTileID} from '../../source/tile_id';\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 = (\n matrix: Float32Array,\n opacity: number,\n color: Color\n): UniformValues => ({\n 'u_matrix': matrix,\n 'u_opacity': opacity,\n 'u_color': color\n});\n\nconst backgroundPatternUniformValues = (\n matrix: Float32Array,\n opacity: number,\n painter: Painter,\n image: CrossFaded,\n tile: {tileID: OverscaledTileID, tileSize: number},\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","// @flow\n\nimport { fillExtrusionUniforms, fillExtrusionPatternUniforms } from './fill_extrusion_program';\nimport { fillUniforms, fillPatternUniforms, fillOutlineUniforms, fillOutlinePatternUniforms } from './fill_program';\nimport { circleUniforms } from './circle_program';\nimport { collisionUniforms } 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 } from './symbol_program';\nimport { backgroundUniforms, backgroundPatternUniforms } from './background_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: collisionUniforms,\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 background: backgroundUniforms,\n backgroundPattern: backgroundPatternUniforms\n};\n","// @flow\n\nimport { OverscaledTileID, CanonicalTileID } from '../source/tile_id';\n\nimport type Tile from './../source/tile';\nimport type Context from '../gl/context';\n\nexport type Mask = {\n [number]: CanonicalTileID\n};\n\n// Updates the TileMasks for all renderable tiles. A TileMask describes all regions\n// within that tile that are *not* covered by other renderable tiles.\n// Example: renderableTiles in our list are 2/1/3, 3/3/6, and 4/5/13. The schematic for creating the\n// TileMask for 2/1/3 looks like this:\n//\n// ┌────────┬────────┬─────────────────┐\n// │ │ │#################│\n// │ 4/4/12 │ 4/5/12 │#################│\n// │ │ │#################│\n// ├──────3/2/6──────┤#####3/3/6#######│\n// │ │########│#################│\n// │ 4/4/13 │#4/5/13#│#################│\n// │ │########│#################│\n// ├────────┴──────2/1/3───────────────┤\n// │ │ │\n// │ │ │\n// │ │ │\n// │ 3/2/7 │ 3/3/7 │\n// │ │ │\n// │ │ │\n// │ │ │\n// └─────────────────┴─────────────────┘\n//\n// The TileMask for 2/1/3 thus consists of the tiles 4/4/12, 4/5/12, 4/4/13, 3/2/7, and 3/3/7,\n// but it does *not* include 4/5/13, and 3/3/6, since these are other renderableTiles.\n// A TileMask always contains TileIDs *relative* to the tile it is generated for, so 2/1/3 is\n// \"subtracted\" from these TileIDs. The final TileMask for 2/1/3 will thus be:\n//\n// ┌────────┬────────┬─────────────────┐\n// │ │ │#################│\n// │ 2/0/0 │ 2/1/0 │#################│\n// │ │ │#################│\n// ├────────┼────────┤#################│\n// │ │########│#################│\n// │ 2/0/1 │########│#################│\n// │ │########│#################│\n// ├────────┴────────┼─────────────────┤\n// │ │ │\n// │ │ │\n// │ │ │\n// │ 1/0/1 │ 1/1/1 │\n// │ │ │\n// │ │ │\n// │ │ │\n// └─────────────────┴─────────────────┘\n//\n// Only other renderable tiles that are *children* of the tile we are generating the mask for will\n// be considered. For example, adding TileID 4/8/13 to renderableTiles won't affect the TileMask for\n// 2/1/3, since it is not a descendant of it.\n\nexport default function(renderableTiles: Array, context: Context) {\n const sortedRenderables = renderableTiles.sort((a, b) => { return a.tileID.isLessThan(b.tileID) ? -1 : b.tileID.isLessThan(a.tileID) ? 1 : 0; });\n\n for (let i = 0; i < sortedRenderables.length; i++) {\n const mask = {};\n const tile = sortedRenderables[i];\n const childArray = sortedRenderables.slice(i + 1);\n // Try to add all remaining ids as children. We sorted the tile list\n // by z earlier, so all preceding items cannot be children of the current\n // tile. We also compute the lower bound of the next wrap, because items of the next wrap\n // can never be children of the current wrap.\n\n computeTileMasks(tile.tileID.wrapped(), tile.tileID, childArray, new OverscaledTileID(0, tile.tileID.wrap + 1, 0, 0, 0), mask);\n tile.setMask(mask, context);\n }\n}\n\nfunction computeTileMasks(rootTile: OverscaledTileID, ref: OverscaledTileID, childArray: Array, lowerBound: OverscaledTileID, mask: Mask) {\n // If the reference or any of its children is found in the list, we need to recurse.\n for (let i = 0; i < childArray.length; i++) {\n const childTile = childArray[i];\n // childTile is from a larger wrap than the rootTile so it cannot be a child tile\n if (lowerBound.isLessThan(childTile.tileID)) break;\n // The current tile is masked out, so we don't need to add them to the mask set.\n if (ref.key === childTile.tileID.key) {\n return;\n } else if (childTile.tileID.isChildOf(ref)) {\n // There's at least one child tile that is masked out, so recursively descend\n const children = ref.children(Infinity);\n for (let j = 0; j < children.length; j++) {\n const child = children[j];\n computeTileMasks(rootTile, child, childArray.slice(i), lowerBound, mask);\n }\n return;\n }\n }\n // We couldn't find a child, so it's definitely a masked part.\n // Compute the difference between the root tile ID and the reference tile ID, since TileMask\n // elements are always relative (see below for explanation).\n const diffZ = ref.overscaledZ - rootTile.overscaledZ;\n const maskTileId = new CanonicalTileID(diffZ, ref.canonical.x - (rootTile.canonical.x << diffZ), ref.canonical.y - (rootTile.canonical.y << diffZ));\n mask[maskTileId.key] = mask[maskTileId.key] || maskTileId;\n}\n","// @flow\n\nimport 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 } from './program/collision_program';\n\nexport default drawCollisionDebug;\n\nfunction drawCollisionDebugGeometry(painter: Painter, sourceCache: SourceCache, layer: StyleLayer, coords: Array, drawCircles: boolean) {\n const context = painter.context;\n const gl = context.gl;\n const program = drawCircles ? painter.useProgram('collisionCircle') : painter.useProgram('collisionBox');\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): any);\n if (!bucket) continue;\n const buffers = drawCircles ? bucket.collisionCircle : bucket.collisionBox;\n if (!buffers) continue;\n\n program.draw(context, drawCircles ? gl.TRIANGLES : gl.LINES,\n DepthMode.disabled, StencilMode.disabled,\n painter.colorModeForRenderPass(),\n CullFaceMode.disabled,\n collisionUniformValues(\n coord.posMatrix,\n painter.transform,\n tile),\n layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer,\n buffers.segments, null, painter.transform.zoom, null, null,\n buffers.collisionVertexBuffer);\n }\n}\n\nfunction drawCollisionDebug(painter: Painter, sourceCache: SourceCache, layer: StyleLayer, coords: Array) {\n drawCollisionDebugGeometry(painter, sourceCache, layer, coords, false);\n drawCollisionDebugGeometry(painter, sourceCache, layer, coords, true);\n}\n","// @flow\n\nimport 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 * as symbolSize from '../symbol/symbol_size';\nimport { mat4 } from 'gl-matrix';\nconst identityMat4 = mat4.identity(new Float32Array(16));\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';\nimport { evaluateRadialOffset } from '../symbol/symbol_layout';\n\nimport {\n symbolIconUniformValues,\n symbolSDFUniformValues\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';\nimport type SymbolBucket, {SymbolBuffers} from '../data/bucket/symbol_bucket';\nimport type Texture from '../render/texture';\nimport type {OverscaledTileID} 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';\n\nexport default drawSymbols;\n\ntype SymbolTileRenderState = {\n segments: SegmentVector,\n sortKey: number,\n state: {\n program: any,\n buffers: SymbolBuffers,\n uniformValues: any,\n atlasTexture: Texture,\n atlasInterpolation: any,\n isSDF: boolean,\n hasHalo: boolean\n }\n};\n\nfunction drawSymbols(painter: Painter, sourceCache: SourceCache, layer: SymbolStyleLayer, coords: Array, variableOffsets: {[CrossTileID]: VariableOffset}) {\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\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, variableOffsets\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, variableOffsets\n );\n }\n\n if (sourceCache.map.showCollisionBoxes) {\n drawCollisionDebug(painter, sourceCache, layer, coords);\n }\n}\n\nfunction calculateVariableRenderShift(anchor, width, height, radialOffset, textBoxScale, renderTextSize): Point {\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);\n const shiftX = -(horizontalAlign - 0.5) * width;\n const shiftY = -(verticalAlign - 0.5) * height;\n const offset = evaluateRadialOffset(anchor, radialOffset);\n return new Point(\n (shiftX / textBoxScale + offset[0]) * renderTextSize,\n (shiftY / textBoxScale + offset[1]) * renderTextSize\n );\n}\n\nfunction updateVariableAnchors(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize,\n transform, labelPlaneMatrix, posMatrix, tileScale, size) {\n const placedSymbols = bucket.text.placedSymbolArray;\n const dynamicLayoutVertexArray = bucket.text.dynamicLayoutVertexArray;\n dynamicLayoutVertexArray.clear();\n for (let s = 0; s < placedSymbols.length; s++) {\n const symbol: any = placedSymbols.get(s);\n const skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation;\n const variableOffset = (!symbol.hidden && symbol.crossTileID && !skipOrientation) ? variableOffsets[symbol.crossTileID] : null;\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, dynamicLayoutVertexArray);\n } else {\n const tileAnchor = new Point(symbol.anchorX, symbol.anchorY);\n const projectedAnchor = symbolProjection.project(tileAnchor, pitchWithMap ? posMatrix : labelPlaneMatrix);\n const perspectiveRatio = 0.5 + 0.5 * (transform.cameraToCenterDistance / projectedAnchor.signedDistanceFromCamera);\n let renderTextSize = symbolSize.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, radialOffset, textBoxScale } = variableOffset;\n\n const shift = calculateVariableRenderShift(\n variableOffset.anchor, width, height, radialOffset, textBoxScale, renderTextSize);\n\n // Usual case is that we take the projected anchor and add the pixel-based shift\n // calculated above. 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 shiftedAnchor = pitchWithMap ?\n symbolProjection.project(tileAnchor.add(shift), labelPlaneMatrix).point :\n projectedAnchor.point.add(rotateWithMap ?\n shift.rotate(-transform.angle) :\n shift);\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(dynamicLayoutVertexArray, shiftedAnchor, angle);\n }\n }\n }\n bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);\n}\n\nfunction updateVerticalLabels(bucket) {\n const placedSymbols = bucket.text.placedSymbolArray;\n const dynamicLayoutVertexArray = bucket.text.dynamicLayoutVertexArray;\n dynamicLayoutVertexArray.clear();\n for (let s = 0; s < placedSymbols.length; s++) {\n const symbol: any = placedSymbols.get(s);\n const shouldHide = symbol.hidden || !symbol.placedOrientation;\n if (shouldHide) {\n // These symbols are from an orientation 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, dynamicLayoutVertexArray);\n } else {\n const tileAnchor = new Point(symbol.anchorX, symbol.anchorY);\n const angle = (bucket.allowVerticalPlacement && symbol.placedOrientation === WritingMode.vertical) ? Math.PI / 2 : 0;\n\n for (let g = 0; g < symbol.numGlyphs; g++) {\n addDynamicAttributes(dynamicLayoutVertexArray, tileAnchor, angle);\n }\n }\n }\n bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);\n}\n\nfunction drawLayerSymbols(painter, sourceCache, layer, coords, isText, translate, translateAnchor,\n rotationAlignment, pitchAlignment, keepUpright, stencilMode, colorMode, variableOffsets) {\n\n const context = painter.context;\n const gl = context.gl;\n const tr = painter.transform;\n\n const rotateWithMap = rotationAlignment === 'map';\n const pitchWithMap = pitchAlignment === 'map';\n const alongLine = rotateWithMap && 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 sortFeaturesByKey = layer.layout.get('symbol-sort-key').constantOr(1) !== undefined;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n\n let program;\n let size;\n const variablePlacement = layer.layout.get('text-variable-anchor');\n\n const tileRenderState: Array = [];\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n const bucket: SymbolBucket = (tile.getBucket(layer): any);\n if (!bucket) continue;\n const buffers = isText ? bucket.text : bucket.icon;\n if (!buffers || !buffers.segments.get().length) 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\n if (!program) {\n program = painter.useProgram(isSDF ? 'symbolSDF' : 'symbolIcon', programConfiguration);\n size = symbolSize.evaluateSizeForZoom(sizeData, tr.zoom);\n }\n\n context.activeTexture.set(gl.TEXTURE0);\n\n let texSize: [number, number];\n let atlasTexture;\n let atlasInterpolation;\n if (isText) {\n atlasTexture = tile.glyphAtlasTexture;\n atlasInterpolation = gl.LINEAR;\n texSize = tile.glyphAtlasTexture.size;\n\n } else {\n const iconScaled = layer.layout.get('icon-size').constantOr(0) !== 1 || bucket.iconsNeedLinear;\n const iconTransformed = pitchWithMap || tr.pitch !== 0;\n\n atlasTexture = tile.imageAtlasTexture;\n atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || iconTransformed ?\n gl.LINEAR :\n gl.NEAREST;\n texSize = tile.imageAtlasTexture.size;\n }\n\n const s = pixelsToTileUnits(tile, 1, painter.transform.zoom);\n const labelPlaneMatrix = symbolProjection.getLabelPlaneMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s);\n const glCoordMatrix = symbolProjection.getGlCoordMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s);\n\n if (alongLine) {\n symbolProjection.updateLineLabels(bucket, coord.posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrix, pitchWithMap, keepUpright);\n } else if (isText && size && variablePlacement) {\n const tileScale = Math.pow(2, tr.zoom - tile.tileID.overscaledZ);\n updateVariableAnchors(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize,\n tr, labelPlaneMatrix, coord.posMatrix, tileScale, size);\n } else if (isText && size && bucket.allowVerticalPlacement) {\n updateVerticalLabels(bucket);\n }\n\n const matrix = painter.translatePosMatrix(coord.posMatrix, tile, translate, translateAnchor),\n uLabelPlaneMatrix = (alongLine || (isText && variablePlacement)) ? identityMat4 : labelPlaneMatrix,\n uglCoordMatrix = painter.translatePosMatrix(glCoordMatrix, tile, translate, translateAnchor, true);\n\n const hasHalo = isSDF && layer.paint.get(isText ? 'text-halo-width' : 'icon-halo-width').constantOr(1) !== 0;\n\n let uniformValues;\n if (isSDF) {\n uniformValues = symbolSDFUniformValues(sizeData.kind,\n size, rotateInShader, pitchWithMap, painter, matrix,\n uLabelPlaneMatrix, uglCoordMatrix, isText, texSize, true);\n\n } else {\n uniformValues = symbolIconUniformValues(sizeData.kind,\n size, rotateInShader, pitchWithMap, painter, matrix,\n uLabelPlaneMatrix, uglCoordMatrix, isText, texSize);\n }\n\n const state = {\n program,\n buffers,\n uniformValues,\n atlasTexture,\n atlasInterpolation,\n isSDF,\n hasHalo\n };\n\n if (sortFeaturesByKey) {\n const oldSegments = buffers.segments.get();\n for (const segment of oldSegments) {\n tileRenderState.push({\n segments: new SegmentVector([segment]),\n sortKey: ((segment.sortKey: any): number),\n state\n });\n }\n } else {\n tileRenderState.push({\n segments: buffers.segments,\n sortKey: 0,\n state\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 state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE);\n\n if (state.isSDF) {\n const uniformValues = ((state.uniformValues: any): 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);\n }\n uniformValues['u_is_halo'] = 0;\n }\n drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, state.uniformValues);\n }\n}\n\nfunction drawSymbolElements(buffers, segments, layer, painter, program, depthMode, stencilMode, colorMode, uniformValues) {\n const context = painter.context;\n const gl = context.gl;\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, 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","// @flow\n\nimport Color from '../style-spec/util/color';\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_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';\n\nexport default drawFill;\n\nfunction 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: 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(painter, sourceCache, layer, coords, depthMode, colorMode, isOutline) {\n const gl = painter.context.gl;\n\n const patternProperty = layer.paint.get('fill-pattern');\n const image = patternProperty && patternProperty.constantOr((1: 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 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): any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram(programName, programConfiguration);\n\n if (image) {\n painter.context.activeTexture.set(gl.TEXTURE0);\n tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n programConfiguration.updatePatternPaintBuffers(crossfade);\n }\n\n const constantPattern = patternProperty.constantOr(null);\n if (constantPattern && tile.imageAtlas) {\n const posTo = tile.imageAtlas.patternPositions[constantPattern.to];\n const posFrom = tile.imageAtlas.patternPositions[constantPattern.from];\n if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);\n }\n\n const tileMatrix = painter.translatePosMatrix(coord.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];\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,\n layer.id, bucket.layoutVertexBuffer, indexBuffer, segments,\n layer.paint, painter.transform.zoom, programConfiguration);\n }\n}\n","// @flow\n\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 {\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\nexport default draw;\n\nfunction draw(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: 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(painter, source, layer, coords, depthMode, stencilMode, colorMode) {\n const context = painter.context;\n const gl = context.gl;\n const patternProperty = layer.paint.get('fill-extrusion-pattern');\n const image = patternProperty.constantOr((1: any));\n const crossfade = layer.getCrossfadeParameters();\n const opacity = layer.paint.get('fill-extrusion-opacity');\n\n for (const coord of coords) {\n const tile = source.getTile(coord);\n const bucket: ?FillExtrusionBucket = (tile.getBucket(layer): any);\n if (!bucket) continue;\n\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.updatePatternPaintBuffers(crossfade);\n }\n\n const constantPattern = patternProperty.constantOr(null);\n if (constantPattern && tile.imageAtlas) {\n const posTo = tile.imageAtlas.patternPositions[constantPattern.to];\n const posFrom = tile.imageAtlas.patternPositions[constantPattern.from];\n if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);\n }\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, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer,\n bucket.segments, layer.paint, painter.transform.zoom,\n programConfiguration);\n }\n}\n","// @flow\n\nimport Texture from './texture';\nimport StencilMode from '../gl/stencil_mode';\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\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 default drawHillshade;\n\nfunction 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 const sourceMaxZoom = sourceCache.getSource().maxzoom;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n const stencilMode = StencilMode.disabled;\n const colorMode = painter.colorModeForRenderPass();\n\n for (const tileID of tileIDs) {\n const tile = sourceCache.getTile(tileID);\n if (tile.needsHillshadePrepare && painter.renderPass === 'offscreen') {\n prepareHillshade(painter, tile, layer, sourceMaxZoom, depthMode, stencilMode, colorMode);\n continue;\n } else if (painter.renderPass === 'translucent') {\n renderHillshade(painter, tile, layer, depthMode, stencilMode, colorMode);\n }\n }\n\n context.viewport.set([0, 0, painter.width, painter.height]);\n}\n\nfunction renderHillshade(painter, tile, layer, depthMode, stencilMode, colorMode) {\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\n context.activeTexture.set(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n\n const uniformValues = hillshadeUniformValues(painter, tile, layer);\n\n if (tile.maskedBoundsBuffer && tile.maskedIndexBuffer && tile.segments) {\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, tile.maskedBoundsBuffer,\n tile.maskedIndexBuffer, tile.segments);\n } else {\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, 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(painter, tile, layer, sourceMaxZoom, depthMode, stencilMode, colorMode) {\n const context = painter.context;\n const gl = context.gl;\n // decode rgba levels by using integer overflow to convert each Uint32Array element -> 4 Uint8Array elements.\n // ex.\n // Uint32:\n // base 10 - 67308\n // base 2 - 0000 0000 0000 0001 0000 0110 1110 1100\n //\n // Uint8:\n // base 10 - 0, 1, 6, 236 (this order is reversed in the resulting array via the overflow.\n // first 8 bits represent 236, so the r component of the texture pixel will be 236 etc.)\n // base 2 - 0000 0000, 0000 0001, 0000 0110, 1110 1100\n if (tile.dem && tile.dem.data) {\n const tileSize = tile.dem.dim;\n const textureStride = tile.dem.stride;\n\n const pixelData = tile.dem.getPixels();\n context.activeTexture.set(gl.TEXTURE1);\n\n // if UNPACK_PREMULTIPLY_ALPHA_WEBGL is set to true prior to drawHillshade being called\n // tiles will appear blank, because as you can see above the alpha value for these textures\n // is always 0\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);\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, sourceMaxZoom),\n layer.id, painter.rasterBoundsBuffer,\n painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n\n tile.needsHillshadePrepare = false;\n }\n}\n","// @flow\n\nimport { 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 default drawRaster;\n\nfunction drawRaster(painter: Painter, sourceCache: SourceCache, layer: RasterStyleLayer, coords: Array) {\n if (painter.renderPass !== 'translucent') return;\n if (layer.paint.get('raster-opacity') === 0) 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 stencilMode = StencilMode.disabled;\n const colorMode = painter.colorModeForRenderPass();\n const minTileZ = coords.length && coords[0].overscaledZ;\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 const posMatrix = painter.transform.calculatePosMatrix(coord.toUnwrapped(), align);\n\n tile.registerFadeDuration(layer.paint.get('raster-fade-duration'));\n\n const parentTile = sourceCache.findLoadedParent(coord, 0),\n fade = getFadeValues(tile, parentTile, sourceCache, layer, painter.transform);\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 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, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, source.boundsBuffer,\n painter.quadTriangleIndexBuffer, source.boundsSegments);\n } else if (tile.maskedBoundsBuffer && tile.maskedIndexBuffer && tile.segments) {\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, tile.maskedBoundsBuffer,\n tile.maskedIndexBuffer, tile.segments, layer.paint,\n painter.transform.zoom);\n } else {\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, painter.rasterBoundsBuffer,\n painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n }\n }\n}\n\nfunction getFadeValues(tile, parentTile, sourceCache, layer, transform) {\n const fadeDuration = layer.paint.get('raster-fade-duration');\n\n if (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","// @flow\n\nimport { mat4 } from 'gl-matrix';\nimport EXTENT from '../data/extent';\nimport { PosArray } from '../data/array_types';\nimport { LineIndexArray } from '../data/index_array_type';\nimport posAttributes from '../data/pos_attributes';\nimport SegmentVector from '../data/segment';\nimport 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 '../style-spec/util/color';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport default drawDebug;\n\nfunction 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, sourceCache, coord) {\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\n program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n debugUniformValues(posMatrix, Color.red), id,\n painter.debugBuffer, painter.tileBorderIndexBuffer, painter.debugSegments);\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);\n const vertices = createTextVertices(`${coord.toString()} ${tileSizeKb}kb`, 50, 200 * scaleRatio, 5 * scaleRatio);\n const debugTextArray = new PosArray();\n const debugTextIndices = new LineIndexArray();\n for (let v = 0; v < vertices.length; v += 2) {\n debugTextArray.emplaceBack(vertices[v], vertices[v + 1]);\n debugTextIndices.emplaceBack(v, v + 1);\n }\n const debugTextBuffer = context.createVertexBuffer(debugTextArray, posAttributes.members);\n const debugTextIndexBuffer = context.createIndexBuffer(debugTextIndices);\n const debugTextSegment = SegmentVector.simpleSegment(0, 0, debugTextArray.length / 2, debugTextArray.length / 2);\n\n // Draw the halo with multiple 1px lines instead of one wider line because\n // the gl spec doesn't guarantee support for lines with width > 1.\n const onePixel = EXTENT / (Math.pow(2, painter.transform.zoom - coord.overscaledZ) * tileSize * scaleRatio);\n\n const haloWidth = 1;\n const translations = [];\n for (let x = -haloWidth; x <= haloWidth; x++) {\n for (let y = -haloWidth; y <= haloWidth; y++) {\n if (x === 0 && y === 0) {\n // don't draw the halo at 0,0 since the text is drawn there\n break;\n }\n\n translations.push([x, y]);\n }\n }\n\n for (let i = 0; i < translations.length; i++) {\n const translation = translations[i];\n\n program.draw(context, gl.LINES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n debugUniformValues(\n mat4.translate([], posMatrix, [\n onePixel * translation[0],\n onePixel * translation[1], 0]),\n Color.white),\n id, debugTextBuffer, debugTextIndexBuffer, debugTextSegment);\n }\n\n program.draw(context, gl.LINES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n debugUniformValues(posMatrix, Color.black), id,\n debugTextBuffer, debugTextIndexBuffer, debugTextSegment);\n}\n\n// Font data From Hershey Simplex Font\n// http://paulbourke.net/dataformats/hershey/\nconst simplexFont = {\n \" \": [16, []],\n \"!\": [10, [5, 21, 5, 7, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2]],\n \"\\\"\": [16, [4, 21, 4, 14, -1, -1, 12, 21, 12, 14]],\n \"#\": [21, [11, 25, 4, -7, -1, -1, 17, 25, 10, -7, -1, -1, 4, 12, 18, 12, -1, -1, 3, 6, 17, 6]],\n \"$\": [20, [8, 25, 8, -4, -1, -1, 12, 25, 12, -4, -1, -1, 17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3]],\n \"%\": [24, [21, 21, 3, 0, -1, -1, 8, 21, 10, 19, 10, 17, 9, 15, 7, 14, 5, 14, 3, 16, 3, 18, 4, 20, 6, 21, 8, 21, 10, 20, 13, 19, 16, 19, 19, 20, 21, 21, -1, -1, 17, 7, 15, 6, 14, 4, 14, 2, 16, 0, 18, 0, 20, 1, 21, 3, 21, 5, 19, 7, 17, 7]],\n \"&\": [26, [23, 12, 23, 13, 22, 14, 21, 14, 20, 13, 19, 11, 17, 6, 15, 3, 13, 1, 11, 0, 7, 0, 5, 1, 4, 2, 3, 4, 3, 6, 4, 8, 5, 9, 12, 13, 13, 14, 14, 16, 14, 18, 13, 20, 11, 21, 9, 20, 8, 18, 8, 16, 9, 13, 11, 10, 16, 3, 18, 1, 20, 0, 22, 0, 23, 1, 23, 2]],\n \"'\": [10, [5, 19, 4, 20, 5, 21, 6, 20, 6, 18, 5, 16, 4, 15]],\n \"(\": [14, [11, 25, 9, 23, 7, 20, 5, 16, 4, 11, 4, 7, 5, 2, 7, -2, 9, -5, 11, -7]],\n \")\": [14, [3, 25, 5, 23, 7, 20, 9, 16, 10, 11, 10, 7, 9, 2, 7, -2, 5, -5, 3, -7]],\n \"*\": [16, [8, 21, 8, 9, -1, -1, 3, 18, 13, 12, -1, -1, 13, 18, 3, 12]],\n \"+\": [26, [13, 18, 13, 0, -1, -1, 4, 9, 22, 9]],\n \",\": [10, [6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4]],\n \"-\": [26, [4, 9, 22, 9]],\n \".\": [10, [5, 2, 4, 1, 5, 0, 6, 1, 5, 2]],\n \"/\": [22, [20, 25, 2, -7]],\n \"0\": [20, [9, 21, 6, 20, 4, 17, 3, 12, 3, 9, 4, 4, 6, 1, 9, 0, 11, 0, 14, 1, 16, 4, 17, 9, 17, 12, 16, 17, 14, 20, 11, 21, 9, 21]],\n \"1\": [20, [6, 17, 8, 18, 11, 21, 11, 0]],\n \"2\": [20, [4, 16, 4, 17, 5, 19, 6, 20, 8, 21, 12, 21, 14, 20, 15, 19, 16, 17, 16, 15, 15, 13, 13, 10, 3, 0, 17, 0]],\n \"3\": [20, [5, 21, 16, 21, 10, 13, 13, 13, 15, 12, 16, 11, 17, 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4]],\n \"4\": [20, [13, 21, 3, 7, 18, 7, -1, -1, 13, 21, 13, 0]],\n \"5\": [20, [15, 21, 5, 21, 4, 12, 5, 13, 8, 14, 11, 14, 14, 13, 16, 11, 17, 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4]],\n \"6\": [20, [16, 18, 15, 20, 12, 21, 10, 21, 7, 20, 5, 17, 4, 12, 4, 7, 5, 3, 7, 1, 10, 0, 11, 0, 14, 1, 16, 3, 17, 6, 17, 7, 16, 10, 14, 12, 11, 13, 10, 13, 7, 12, 5, 10, 4, 7]],\n \"7\": [20, [17, 21, 7, 0, -1, -1, 3, 21, 17, 21]],\n \"8\": [20, [8, 21, 5, 20, 4, 18, 4, 16, 5, 14, 7, 13, 11, 12, 14, 11, 16, 9, 17, 7, 17, 4, 16, 2, 15, 1, 12, 0, 8, 0, 5, 1, 4, 2, 3, 4, 3, 7, 4, 9, 6, 11, 9, 12, 13, 13, 15, 14, 16, 16, 16, 18, 15, 20, 12, 21, 8, 21]],\n \"9\": [20, [16, 14, 15, 11, 13, 9, 10, 8, 9, 8, 6, 9, 4, 11, 3, 14, 3, 15, 4, 18, 6, 20, 9, 21, 10, 21, 13, 20, 15, 18, 16, 14, 16, 9, 15, 4, 13, 1, 10, 0, 8, 0, 5, 1, 4, 3]],\n \":\": [10, [5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2]],\n \";\": [10, [5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4]],\n \"<\": [24, [20, 18, 4, 9, 20, 0]],\n \"=\": [26, [4, 12, 22, 12, -1, -1, 4, 6, 22, 6]],\n \">\": [24, [4, 18, 20, 9, 4, 0]],\n \"?\": [18, [3, 16, 3, 17, 4, 19, 5, 20, 7, 21, 11, 21, 13, 20, 14, 19, 15, 17, 15, 15, 14, 13, 13, 12, 9, 10, 9, 7, -1, -1, 9, 2, 8, 1, 9, 0, 10, 1, 9, 2]],\n \"@\": [27, [18, 13, 17, 15, 15, 16, 12, 16, 10, 15, 9, 14, 8, 11, 8, 8, 9, 6, 11, 5, 14, 5, 16, 6, 17, 8, -1, -1, 12, 16, 10, 14, 9, 11, 9, 8, 10, 6, 11, 5, -1, -1, 18, 16, 17, 8, 17, 6, 19, 5, 21, 5, 23, 7, 24, 10, 24, 12, 23, 15, 22, 17, 20, 19, 18, 20, 15, 21, 12, 21, 9, 20, 7, 19, 5, 17, 4, 15, 3, 12, 3, 9, 4, 6, 5, 4, 7, 2, 9, 1, 12, 0, 15, 0, 18, 1, 20, 2, 21, 3, -1, -1, 19, 16, 18, 8, 18, 6, 19, 5]],\n \"A\": [18, [9, 21, 1, 0, -1, -1, 9, 21, 17, 0, -1, -1, 4, 7, 14, 7]],\n \"B\": [21, [4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, 11, -1, -1, 4, 11, 13, 11, 16, 10, 17, 9, 18, 7, 18, 4, 17, 2, 16, 1, 13, 0, 4, 0]],\n \"C\": [21, [18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5]],\n \"D\": [21, [4, 21, 4, 0, -1, -1, 4, 21, 11, 21, 14, 20, 16, 18, 17, 16, 18, 13, 18, 8, 17, 5, 16, 3, 14, 1, 11, 0, 4, 0]],\n \"E\": [19, [4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11, -1, -1, 4, 0, 17, 0]],\n \"F\": [18, [4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11]],\n \"G\": [21, [18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 18, 8, -1, -1, 13, 8, 18, 8]],\n \"H\": [22, [4, 21, 4, 0, -1, -1, 18, 21, 18, 0, -1, -1, 4, 11, 18, 11]],\n \"I\": [8, [4, 21, 4, 0]],\n \"J\": [16, [12, 21, 12, 5, 11, 2, 10, 1, 8, 0, 6, 0, 4, 1, 3, 2, 2, 5, 2, 7]],\n \"K\": [21, [4, 21, 4, 0, -1, -1, 18, 21, 4, 7, -1, -1, 9, 12, 18, 0]],\n \"L\": [17, [4, 21, 4, 0, -1, -1, 4, 0, 16, 0]],\n \"M\": [24, [4, 21, 4, 0, -1, -1, 4, 21, 12, 0, -1, -1, 20, 21, 12, 0, -1, -1, 20, 21, 20, 0]],\n \"N\": [22, [4, 21, 4, 0, -1, -1, 4, 21, 18, 0, -1, -1, 18, 21, 18, 0]],\n \"O\": [22, [9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21]],\n \"P\": [21, [4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 14, 17, 12, 16, 11, 13, 10, 4, 10]],\n \"Q\": [22, [9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, -1, -1, 12, 4, 18, -2]],\n \"R\": [21, [4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, 11, 4, 11, -1, -1, 11, 11, 18, 0]],\n \"S\": [20, [17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3]],\n \"T\": [16, [8, 21, 8, 0, -1, -1, 1, 21, 15, 21]],\n \"U\": [22, [4, 21, 4, 6, 5, 3, 7, 1, 10, 0, 12, 0, 15, 1, 17, 3, 18, 6, 18, 21]],\n \"V\": [18, [1, 21, 9, 0, -1, -1, 17, 21, 9, 0]],\n \"W\": [24, [2, 21, 7, 0, -1, -1, 12, 21, 7, 0, -1, -1, 12, 21, 17, 0, -1, -1, 22, 21, 17, 0]],\n \"X\": [20, [3, 21, 17, 0, -1, -1, 17, 21, 3, 0]],\n \"Y\": [18, [1, 21, 9, 11, 9, 0, -1, -1, 17, 21, 9, 11]],\n \"Z\": [20, [17, 21, 3, 0, -1, -1, 3, 21, 17, 21, -1, -1, 3, 0, 17, 0]],\n \"[\": [14, [4, 25, 4, -7, -1, -1, 5, 25, 5, -7, -1, -1, 4, 25, 11, 25, -1, -1, 4, -7, 11, -7]],\n \"\\\\\": [14, [0, 21, 14, -3]],\n \"]\": [14, [9, 25, 9, -7, -1, -1, 10, 25, 10, -7, -1, -1, 3, 25, 10, 25, -1, -1, 3, -7, 10, -7]],\n \"^\": [16, [6, 15, 8, 18, 10, 15, -1, -1, 3, 12, 8, 17, 13, 12, -1, -1, 8, 17, 8, 0]],\n \"_\": [16, [0, -2, 16, -2]],\n \"`\": [10, [6, 21, 5, 20, 4, 18, 4, 16, 5, 15, 6, 16, 5, 17]],\n \"a\": [19, [15, 14, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3]],\n \"b\": [19, [4, 21, 4, 0, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3]],\n \"c\": [18, [15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3]],\n \"d\": [19, [15, 21, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3]],\n \"e\": [18, [3, 8, 15, 8, 15, 10, 14, 12, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3]],\n \"f\": [12, [10, 21, 8, 21, 6, 20, 5, 17, 5, 0, -1, -1, 2, 14, 9, 14]],\n \"g\": [19, [15, 14, 15, -2, 14, -5, 13, -6, 11, -7, 8, -7, 6, -6, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3]],\n \"h\": [19, [4, 21, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0]],\n \"i\": [8, [3, 21, 4, 20, 5, 21, 4, 22, 3, 21, -1, -1, 4, 14, 4, 0]],\n \"j\": [10, [5, 21, 6, 20, 7, 21, 6, 22, 5, 21, -1, -1, 6, 14, 6, -3, 5, -6, 3, -7, 1, -7]],\n \"k\": [17, [4, 21, 4, 0, -1, -1, 14, 14, 4, 4, -1, -1, 8, 8, 15, 0]],\n \"l\": [8, [4, 21, 4, 0]],\n \"m\": [30, [4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0, -1, -1, 15, 10, 18, 13, 20, 14, 23, 14, 25, 13, 26, 10, 26, 0]],\n \"n\": [19, [4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0]],\n \"o\": [19, [8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, 16, 6, 16, 8, 15, 11, 13, 13, 11, 14, 8, 14]],\n \"p\": [19, [4, 14, 4, -7, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3]],\n \"q\": [19, [15, 14, 15, -7, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3]],\n \"r\": [13, [4, 14, 4, 0, -1, -1, 4, 8, 5, 11, 7, 13, 9, 14, 12, 14]],\n \"s\": [17, [14, 11, 13, 13, 10, 14, 7, 14, 4, 13, 3, 11, 4, 9, 6, 8, 11, 7, 13, 6, 14, 4, 14, 3, 13, 1, 10, 0, 7, 0, 4, 1, 3, 3]],\n \"t\": [12, [5, 21, 5, 4, 6, 1, 8, 0, 10, 0, -1, -1, 2, 14, 9, 14]],\n \"u\": [19, [4, 14, 4, 4, 5, 1, 7, 0, 10, 0, 12, 1, 15, 4, -1, -1, 15, 14, 15, 0]],\n \"v\": [16, [2, 14, 8, 0, -1, -1, 14, 14, 8, 0]],\n \"w\": [22, [3, 14, 7, 0, -1, -1, 11, 14, 7, 0, -1, -1, 11, 14, 15, 0, -1, -1, 19, 14, 15, 0]],\n \"x\": [17, [3, 14, 14, 0, -1, -1, 14, 14, 3, 0]],\n \"y\": [16, [2, 14, 8, 0, -1, -1, 14, 14, 8, 0, 6, -4, 4, -6, 2, -7, 1, -7]],\n \"z\": [17, [14, 14, 3, 0, -1, -1, 3, 14, 14, 14, -1, -1, 3, 0, 14, 0]],\n \"{\": [14, [9, 25, 7, 24, 6, 23, 5, 21, 5, 19, 6, 17, 7, 16, 8, 14, 8, 12, 6, 10, -1, -1, 7, 24, 6, 22, 6, 20, 7, 18, 8, 17, 9, 15, 9, 13, 8, 11, 4, 9, 8, 7, 9, 5, 9, 3, 8, 1, 7, 0, 6, -2, 6, -4, 7, -6, -1, -1, 6, 8, 8, 6, 8, 4, 7, 2, 6, 1, 5, -1, 5, -3, 6, -5, 7, -6, 9, -7]],\n \"|\": [8, [4, 25, 4, -7]],\n \"}\": [14, [5, 25, 7, 24, 8, 23, 9, 21, 9, 19, 8, 17, 7, 16, 6, 14, 6, 12, 8, 10, -1, -1, 7, 24, 8, 22, 8, 20, 7, 18, 6, 17, 5, 15, 5, 13, 6, 11, 10, 9, 6, 7, 5, 5, 5, 3, 6, 1, 7, 0, 8, -2, 8, -4, 7, -6, -1, -1, 8, 8, 6, 6, 6, 4, 7, 2, 8, 1, 9, -1, 9, -3, 8, -5, 7, -6, 5, -7]],\n \"~\": [24, [3, 6, 3, 8, 4, 11, 6, 12, 8, 12, 10, 11, 14, 8, 16, 7, 18, 7, 20, 8, 21, 10, -1, -1, 3, 8, 4, 10, 6, 11, 8, 11, 10, 10, 14, 7, 16, 6, 18, 6, 20, 7, 21, 10, 21, 12]]\n};\n\nfunction createTextVertices(text, left, baseline, scale) {\n scale = scale || 1;\n\n const strokes = [];\n let i, len, j, len2, glyph, x, y, prev;\n\n for (i = 0, len = text.length; i < len; i++) {\n glyph = simplexFont[text[i]];\n if (!glyph) continue;\n prev = null;\n\n for (j = 0, len2 = glyph[1].length; j < len2; j += 2) {\n if (glyph[1][j] === -1 && glyph[1][j + 1] === -1) {\n prev = null;\n\n } else {\n x = left + glyph[1][j] * scale;\n y = baseline - glyph[1][j + 1] * scale;\n if (prev) {\n strokes.push(prev.x, prev.y, x, y);\n }\n prev = {x, y};\n }\n }\n left += glyph[0] * scale;\n }\n\n return strokes;\n}\n","// @flow\n\nimport browser from '../util/browser';\n\nimport { mat4 } 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';\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 * as shaders from '../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 updateTileMasks from './tile_mask';\nimport { clippingMaskUniformValues } from './program/clipping_mask_program';\nimport Color from '../style-spec/util/color';\nimport symbol from './draw_symbol';\nimport circle from './draw_circle';\nimport heatmap from './draw_heatmap';\nimport line from './draw_line';\nimport fill from './draw_fill';\nimport fillExtrusion from './draw_fill_extrusion';\nimport hillshade from './draw_hillshade';\nimport raster from './draw_raster';\nimport background from './draw_background';\nimport debug from './draw_debug';\nimport custom from './draw_custom';\n\nconst draw = {\n symbol,\n circle,\n heatmap,\n line,\n fill,\n 'fill-extrusion': fillExtrusion,\n hillshade,\n raster,\n background,\n debug,\n custom\n};\n\nimport type Transform from '../geo/transform';\nimport type Tile from '../source/tile';\nimport type {OverscaledTileID} from '../source/tile_id';\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';\n\nexport type RenderPass = 'offscreen' | 'opaque' | 'translucent';\n\ntype PainterOptions = {\n showOverdrawInspector: boolean,\n showTileBoundaries: boolean,\n rotating: boolean,\n zooming: boolean,\n moving: boolean,\n fadeDuration: number\n}\n\n/**\n * Initialize a new painter object.\n *\n * @param {Canvas} gl an experimental-webgl drawing context\n * @private\n */\nclass Painter {\n context: Context;\n transform: Transform;\n _tileTextures: { [number]: Array };\n numSublayers: number;\n depthEpsilon: number;\n emptyProgramConfiguration: ProgramConfiguration;\n width: number;\n height: number;\n depthRbo: WebGLRenderbuffer;\n depthRboNeedsClear: boolean;\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: { [number]: 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\n constructor(gl: WebGLRenderingContext, transform: Transform) {\n this.context = new Context(gl);\n this.transform = transform;\n this._tileTextures = {};\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.depthRboNeedsClear = true;\n\n this.emptyProgramConfiguration = new ProgramConfiguration();\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) {\n const gl = this.context.gl;\n\n this.width = width * browser.devicePixelRatio;\n this.height = height * browser.devicePixelRatio;\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 if (this.depthRbo) {\n gl.deleteRenderbuffer(this.depthRbo);\n this.depthRbo = null;\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),\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\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 '$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 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): $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 for (const id in sourceCaches) {\n const sourceCache = sourceCaches[id];\n if (sourceCache.used) {\n sourceCache.prepare(this.context);\n }\n }\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 coordsAscending[id] = sourceCache.getVisibleCoordinates();\n coordsDescending[id] = coordsAscending[id].slice().reverse();\n coordsDescendingSymbol[id] = sourceCache.getVisibleCoordinates(true).reverse();\n }\n\n for (const id in sourceCaches) {\n const sourceCache = sourceCaches[id];\n const source = sourceCache.getSource();\n if (source.type !== 'raster' && source.type !== 'raster-dem') continue;\n const visibleTiles = [];\n for (const coord of coordsAscending[id]) visibleTiles.push(sourceCache.getTile(coord));\n updateTileMasks(visibleTiles, this.context);\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 // 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 this.depthRboNeedsClear = true;\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 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 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 // 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 // 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 for (const id in sourceCaches) {\n draw.debug(this, sourceCaches[id], coordsAscending[id]);\n break;\n }\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 setupOffscreenDepthRenderbuffer(): void {\n const context = this.context;\n // All of the 3D textures will use the same depth renderbuffer.\n if (!this.depthRbo) {\n this.depthRbo = context.createRenderbuffer(context.gl.DEPTH_COMPONENT16, this.width, this.height);\n }\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 draw[layer.type](painter, sourceCache, layer, coords, this.style.placement.variableOffsets);\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 {Float32Array} matrix\n */\n translatePosMatrix(matrix: Float32Array, tile: Tile, translate: [number, number], translateAnchor: 'map' | 'viewport', inViewportPixelUnitsUnits?: boolean) {\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 ];\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): boolean {\n if (!image) return false;\n const imagePosA = this.imageManager.getPattern(image.from);\n const imagePosB = this.imageManager.getPattern(image.to);\n return !imagePosA || !imagePosB;\n }\n\n useProgram(name: string, programConfiguration: ProgramConfiguration = this.emptyProgramConfiguration): Program {\n this.cache = this.cache || {};\n const key = `${name}${programConfiguration.cacheKey || ''}${this._showOverdrawInspector ? '/overdraw' : ''}`;\n if (!this.cache[key]) {\n this.cache[key] = new Program(this.context, shaders[name], programConfiguration, programUniforms[name], this._showOverdrawInspector);\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\nexport default Painter;\n","// @flow\n\nimport 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';\n\nexport default drawCircles;\n\ntype TileRenderState = {\n programConfiguration: ProgramConfiguration,\n program: Program<*>,\n layoutVertexBuffer: VertexBuffer,\n indexBuffer: IndexBuffer,\n uniformValues: UniformValues\n};\n\ntype SegmentsTileRenderState = {\n segments: SegmentVector,\n sortKey: number,\n state: TileRenderState\n};\n\nfunction 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').constantOr(1) !== undefined;\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): 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 uniformValues = circleUniformValues(painter, coord, tile, layer);\n\n const state: TileRenderState = {\n programConfiguration,\n program,\n layoutVertexBuffer,\n indexBuffer,\n uniformValues,\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: any): 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} = segmentsState.state;\n const segments = segmentsState.segments;\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id,\n layoutVertexBuffer, indexBuffer, segments,\n layer.paint, painter.transform.zoom, programConfiguration);\n }\n}\n","// @flow\n\nimport Texture from './texture';\nimport Color from '../style-spec/util/color';\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 {\n heatmapUniformValues,\n heatmapTextureUniformValues\n} from './program/heatmap_program';\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 default drawHeatmap;\n\nfunction drawHeatmap(painter: Painter, sourceCache: SourceCache, layer: HeatmapStyleLayer, coords: Array) {\n if (layer.paint.get('heatmap-opacity') === 0) {\n return;\n }\n\n if (painter.renderPass === 'offscreen') {\n const context = painter.context;\n const gl = context.gl;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\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): 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, stencilMode, colorMode, CullFaceMode.disabled,\n heatmapUniformValues(coord.posMatrix,\n tile, zoom, layer.paint.get('heatmap-intensity')),\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 } else if (painter.renderPass === 'translucent') {\n painter.context.setColorMode(painter.colorModeForRenderPass());\n renderTextureToMap(painter, layer);\n }\n}\n\nfunction bindFramebuffer(context, painter, layer) {\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.heatmapFbo;\n\n if (!fbo) {\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 fbo = layer.heatmapFbo = context.createFramebuffer(painter.width / 4, painter.height / 4);\n\n bindTextureToFramebuffer(context, painter, texture, fbo);\n\n } else {\n gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n context.bindFramebuffer.set(fbo.framebuffer);\n }\n}\n\nfunction bindTextureToFramebuffer(context, painter, texture, fbo) {\n const gl = context.gl;\n // Use the higher precision half-float texture where available (producing much smoother looking heatmaps);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, painter.width / 4, painter.height / 4, 0, gl.RGBA,\n context.extTextureHalfFloat ? context.extTextureHalfFloat.HALF_FLOAT_OES : gl.UNSIGNED_BYTE, null);\n\n fbo.colorAttachment.set(texture);\n\n // If using half-float texture as a render target is not supported, fall back to a low precision texture\n if (context.extTextureHalfFloat && gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {\n context.extTextureHalfFloat = null;\n fbo.colorAttachment.setDirty();\n bindTextureToFramebuffer(context, painter, texture, fbo);\n }\n}\n\nfunction renderTextureToMap(painter, layer) {\n const context = painter.context;\n const gl = context.gl;\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.heatmapFbo;\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 let colorRampTexture = layer.colorRampTexture;\n if (!colorRampTexture) {\n colorRampTexture = layer.colorRampTexture = new Texture(context, layer.colorRamp, gl.RGBA);\n }\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),\n layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer,\n painter.viewportSegments, layer.paint, painter.transform.zoom);\n}\n","// @flow\n\nimport 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';\n\nexport default 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: any));\n\n const gradient = layer.paint.get('line-gradient');\n const crossfade = layer.getCrossfadeParameters();\n\n const programId =\n dasharray ? 'lineSDF' :\n image ? 'linePattern' :\n gradient ? 'lineGradient' : 'line';\n\n const context = painter.context;\n const gl = context.gl;\n\n let firstTile = true;\n\n if (gradient) {\n context.activeTexture.set(gl.TEXTURE0);\n\n let gradientTexture = layer.gradientTexture;\n if (!layer.gradient) return;\n if (!gradientTexture) gradientTexture = layer.gradientTexture = new Texture(context, layer.gradient, gl.RGBA);\n gradientTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n }\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): 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\n const constantPattern = patternProperty.constantOr(null);\n if (constantPattern && tile.imageAtlas) {\n const posTo = tile.imageAtlas.patternPositions[constantPattern.to];\n const posFrom = tile.imageAtlas.patternPositions[constantPattern.from];\n if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);\n }\n\n const uniformValues = dasharray ? lineSDFUniformValues(painter, tile, layer, dasharray, crossfade) :\n image ? linePatternUniformValues(painter, tile, layer, crossfade) :\n gradient ? lineGradientUniformValues(painter, tile, layer) :\n lineUniformValues(painter, tile, layer);\n\n if (dasharray && (programChanged || painter.lineAtlas.dirty)) {\n context.activeTexture.set(gl.TEXTURE0);\n painter.lineAtlas.bind(context);\n } else if (image) {\n context.activeTexture.set(gl.TEXTURE0);\n tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n programConfiguration.updatePatternPaintBuffers(crossfade);\n }\n\n program.draw(context, gl.TRIANGLES, depthMode,\n painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues,\n layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments,\n layer.paint, painter.transform.zoom, programConfiguration);\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","// @flow\n\nimport 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';\n\nexport default drawBackground;\n\nfunction drawBackground(painter: Painter, sourceCache: SourceCache, layer: BackgroundStyleLayer) {\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\n const program = painter.useProgram(image ? 'backgroundPattern' : 'background');\n\n const tileIDs = transform.coveringTiles({tileSize});\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 = painter.transform.calculatePosMatrix(tileID.toUnwrapped());\n\n const uniformValues = image ?\n backgroundPatternUniformValues(matrix, opacity, painter, image, {tileID, tileSize}, crossfade) :\n backgroundUniformValues(matrix, opacity, color);\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, painter.tileExtentBuffer,\n painter.quadTriangleIndexBuffer, painter.tileExtentSegments);\n }\n}\n","// @flow\n\nexport default drawCustom;\n\nimport 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\nfunction 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());\n\n context.setDirty();\n painter.setBaseState();\n context.bindFramebuffer.set(null);\n }\n}\n","// @flow\n\nimport MercatorCoordinate from '../geo/mercator_coordinate';\nimport Point from '@mapbox/point-geometry';\n\nimport { OverscaledTileID } from '../source/tile_id';\n\nexport default tileCover;\n\nfunction tileCover(z: number, bounds: [MercatorCoordinate, MercatorCoordinate, MercatorCoordinate, MercatorCoordinate],\n actualZ: number, renderWorldCopies: boolean | void): Array {\n if (renderWorldCopies === undefined) {\n renderWorldCopies = true;\n }\n const tiles = 1 << z;\n const t = {};\n\n function scanLine(x0, x1, y) {\n let x, w, wx, coord;\n if (y >= 0 && y <= tiles) {\n for (x = x0; x < x1; x++) {\n w = Math.floor(x / tiles);\n wx = (x % tiles + tiles) % tiles;\n if (w === 0 || renderWorldCopies === true) {\n coord = new OverscaledTileID(actualZ, w, z, wx, y);\n t[coord.key] = coord;\n }\n }\n }\n }\n\n const zoomedBounds = bounds.map((coord) => new Point(coord.x, coord.y)._mult(tiles));\n\n // Divide the screen up in two triangles and scan each of them:\n // +---/\n // | / |\n // /---+\n scanTriangle(zoomedBounds[0], zoomedBounds[1], zoomedBounds[2], 0, tiles, scanLine);\n scanTriangle(zoomedBounds[2], zoomedBounds[3], zoomedBounds[0], 0, tiles, scanLine);\n\n return Object.keys(t).map((id) => {\n return t[id];\n });\n}\n\n// Taken from polymaps src/Layer.js\n// https://github.com/simplegeo/polymaps/blob/master/src/Layer.js#L333-L383\n\nfunction edge(a: Point, b: Point) {\n if (a.y > b.y) { const t = a; a = b; b = t; }\n return {\n x0: a.x,\n y0: a.y,\n x1: b.x,\n y1: b.y,\n dx: b.x - a.x,\n dy: b.y - a.y\n };\n}\n\nfunction scanSpans(e0, e1, ymin, ymax, scanLine) {\n const y0 = Math.max(ymin, Math.floor(e1.y0));\n const y1 = Math.min(ymax, Math.ceil(e1.y1));\n\n // sort edges by x-coordinate\n if ((e0.x0 === e1.x0 && e0.y0 === e1.y0) ?\n (e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) :\n (e0.x1 - e1.dy / e0.dy * e0.dx < e1.x0)) {\n const t = e0; e0 = e1; e1 = t;\n }\n\n // scan lines!\n const m0 = e0.dx / e0.dy;\n const m1 = e1.dx / e1.dy;\n const d0 = e0.dx > 0; // use y + 1 to compute x0\n const d1 = e1.dx < 0; // use y + 1 to compute x1\n for (let y = y0; y < y1; y++) {\n const x0 = m0 * Math.max(0, Math.min(e0.dy, y + d0 - e0.y0)) + e0.x0;\n const x1 = m1 * Math.max(0, Math.min(e1.dy, y + d1 - e1.y0)) + e1.x0;\n scanLine(Math.floor(x1), Math.ceil(x0), y);\n }\n}\n\nfunction scanTriangle(a: Point, b: Point, c: Point, ymin, ymax, scanLine) {\n let ab = edge(a, b),\n bc = edge(b, c),\n ca = edge(c, a);\n\n let t;\n\n // sort edges by y-length\n if (ab.dy > bc.dy) { t = ab; ab = bc; bc = t; }\n if (ab.dy > ca.dy) { t = ab; ab = ca; ca = t; }\n if (bc.dy > ca.dy) { t = bc; bc = ca; ca = t; }\n\n // scan span! scan span!\n if (ab.dy) scanSpans(ca, ab, ymin, ymax, scanLine);\n if (bc.dy) scanSpans(ca, bc, ymin, ymax, scanLine);\n}\n\n","// @flow\n\nimport 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 {number as interpolate} from '../style-spec/util/interpolate';\nimport tileCover from '../util/tile_cover';\nimport { UnwrappedTileID } from '../source/tile_id';\nimport EXTENT from '../data/extent';\nimport { vec4, mat4, mat2 } from 'gl-matrix';\n\nimport type { OverscaledTileID, CanonicalTileID } from '../source/tile_id';\n\n/**\n * A single transform, generally used for a single tile to be\n * scaled, rotated, and zoomed.\n * @private\n */\nclass Transform {\n tileSize: number;\n tileZoom: number;\n lngRange: ?[number, number];\n latRange: ?[number, number];\n maxValidLatitude: number;\n scale: number;\n width: number;\n height: number;\n angle: number;\n rotationMatrix: Float64Array;\n zoomFraction: number;\n pixelsToGLUnits: [number, number];\n cameraToCenterDistance: number;\n mercatorMatrix: Array;\n projMatrix: Float64Array;\n alignedProjMatrix: Float64Array;\n pixelMatrix: Float64Array;\n pixelMatrixInverse: Float64Array;\n glCoordMatrix: Float32Array;\n labelPlaneMatrix: Float32Array;\n _fov: number;\n _pitch: number;\n _zoom: number;\n _unmodified: boolean;\n _renderWorldCopies: boolean;\n _minZoom: number;\n _maxZoom: number;\n _center: LngLat;\n _constraining: boolean;\n _posMatrixCache: {[number]: Float32Array};\n _alignedPosMatrixCache: {[number]: Float32Array};\n\n constructor(minZoom: ?number, maxZoom: ?number, renderWorldCopies: boolean | void) {\n this.tileSize = 512; // constant\n this.maxValidLatitude = 85.051129; // constant\n\n this._renderWorldCopies = renderWorldCopies === undefined ? true : renderWorldCopies;\n this._minZoom = minZoom || 0;\n this._maxZoom = maxZoom || 22;\n\n this.setMaxBounds();\n\n this.width = 0;\n this.height = 0;\n this._center = new LngLat(0, 0);\n this.zoom = 0;\n this.angle = 0;\n this._fov = 0.6435011087932844;\n this._pitch = 0;\n this._unmodified = true;\n this._posMatrixCache = {};\n this._alignedPosMatrixCache = {};\n }\n\n clone(): Transform {\n const clone = new Transform(this._minZoom, this._maxZoom, this._renderWorldCopies);\n clone.tileSize = this.tileSize;\n clone.latRange = this.latRange;\n clone.width = this.width;\n clone.height = this.height;\n clone._center = this._center;\n clone.zoom = this.zoom;\n clone.angle = this.angle;\n clone._fov = this._fov;\n clone._pitch = this._pitch;\n clone._unmodified = this._unmodified;\n clone._calcMatrices();\n return clone;\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 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 centerPoint(): Point {\n return 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, 0, 60) / 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 z = Math.min(Math.max(zoom, this.minZoom), this.maxZoom);\n if (this._zoom === z) return;\n this._unmodified = false;\n this._zoom = z;\n this.scale = this.zoomScale(z);\n this.tileZoom = Math.floor(z);\n this.zoomFraction = z - this.tileZoom;\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 * Return a zoom level that will cover all tiles the transform\n * @param {Object} options\n * @param {number} options.tileSize\n * @param {boolean} options.roundZoom\n * @returns {number} zoom level\n */\n coveringZoomLevel(options: {roundZoom?: boolean, tileSize: number}) {\n return (options.roundZoom ? Math.round : Math.floor)(\n this.zoom + this.scaleZoom(this.tileSize / options.tileSize)\n );\n }\n\n /**\n * Return any \"wrapped\" copies of a given tile coordinate that are visible\n * in the current view.\n *\n * @private\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 {Object} options\n * @param {number} options.tileSize\n * @param {number} options.minzoom\n * @param {number} options.maxzoom\n * @param {boolean} options.roundZoom\n * @param {boolean} options.reparseOverscaled\n * @param {boolean} options.renderWorldCopies\n * @returns {Array} 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 }\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 centerCoord = MercatorCoordinate.fromLngLat(this.center);\n const numTiles = Math.pow(2, z);\n const centerPoint = new Point(numTiles * centerCoord.x - 0.5, numTiles * centerCoord.y - 0.5);\n const cornerCoords = [\n this.pointCoordinate(new Point(0, 0)),\n this.pointCoordinate(new Point(this.width, 0)),\n this.pointCoordinate(new Point(this.width, this.height)),\n this.pointCoordinate(new Point(0, this.height))\n ];\n return tileCover(z, cornerCoords, options.reparseOverscaled ? actualZ : z, this._renderWorldCopies)\n .sort((a, b) => centerPoint.dist(a.canonical) - centerPoint.dist(b.canonical));\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 project(lnglat: LngLat) {\n const lat = clamp(lnglat.lat, -this.maxValidLatitude, this.maxValidLatitude);\n return new Point(\n mercatorXfromLng(lnglat.lng) * this.worldSize,\n mercatorYfromLat(lat) * this.worldSize);\n }\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 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 location, return the screen point that corresponds to it\n * @param {LngLat} lnglat location\n * @returns {Point} screen point\n */\n locationPoint(lnglat: LngLat) {\n return this.coordinatePoint(this.locationCoordinate(lnglat));\n }\n\n /**\n * Given a point on screen, return its lnglat\n * @param {Point} p screen point\n * @returns {LngLat} lnglat location\n */\n pointLocation(p: Point) {\n return this.coordinateLocation(this.pointCoordinate(p));\n }\n\n /**\n * Given a geographical lnglat, return an unrounded\n * coordinate that represents it at this transform's zoom level.\n * @param {LngLat} lnglat\n * @returns {Coordinate}\n */\n locationCoordinate(lnglat: LngLat) {\n return MercatorCoordinate.fromLngLat(lnglat);\n }\n\n /**\n * Given a Coordinate, return its geographical position.\n * @param {Coordinate} coord\n * @returns {LngLat} lnglat\n */\n coordinateLocation(coord: MercatorCoordinate) {\n return coord.toLngLat();\n }\n\n pointCoordinate(p: Point) {\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];\n const coord1 = [p.x, p.y, 1, 1];\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 interpolate(x0, x1, t) / this.worldSize,\n interpolate(y0, y1, t) / this.worldSize);\n }\n\n /**\n * Given a coordinate, return the screen point that corresponds to it\n * @param {Coordinate} coord\n * @returns {Point} screen point\n */\n coordinatePoint(coord: MercatorCoordinate) {\n const p = [coord.x * this.worldSize, coord.y * this.worldSize, 0, 1];\n vec4.transformMat4(p, p, this.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 */\n getBounds(): LngLatBounds {\n return new LngLatBounds()\n .extend(this.pointLocation(new Point(0, 0)))\n .extend(this.pointLocation(new Point(this.width, 0)))\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 */\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 * Sets or clears the map's geographical constraints.\n */\n setMaxBounds(bounds?: LngLatBounds) {\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 = [-this.maxValidLatitude, this.maxValidLatitude];\n }\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} unwrappedTileID;\n */\n calculatePosMatrix(unwrappedTileID: UnwrappedTileID, aligned: boolean = false): Float32Array {\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 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 posMatrix = mat4.identity(new Float64Array(16));\n mat4.translate(posMatrix, posMatrix, [unwrappedX * scale, canonical.y * scale, 0]);\n mat4.scale(posMatrix, posMatrix, [scale / EXTENT, scale / EXTENT, 1]);\n mat4.multiply(posMatrix, aligned ? this.alignedProjMatrix : this.projMatrix, posMatrix);\n\n cache[posMatrixKey] = new Float32Array(posMatrix);\n return cache[posMatrixKey];\n }\n\n customLayerMatrix(): Array {\n return this.mercatorMatrix.slice();\n }\n\n _constrain() {\n if (!this.center || !this.width || !this.height || this._constraining) return;\n\n this._constraining = true;\n\n let minY = -90;\n let maxY = 90;\n let minX = -180;\n let maxX = 180;\n let sy, sx, x2, y2;\n const size = this.size,\n unmodified = this._unmodified;\n\n if (this.latRange) {\n const latRange = this.latRange;\n minY = mercatorYfromLat(latRange[1]) * this.worldSize;\n maxY = mercatorYfromLat(latRange[0]) * this.worldSize;\n sy = maxY - minY < size.y ? size.y / (maxY - minY) : 0;\n }\n\n if (this.lngRange) {\n const lngRange = this.lngRange;\n minX = mercatorXfromLng(lngRange[0]) * this.worldSize;\n maxX = mercatorXfromLng(lngRange[1]) * this.worldSize;\n sx = maxX - minX < size.x ? size.x / (maxX - minX) : 0;\n }\n\n const point = this.point;\n\n // how much the map should scale to fit the screen into given latitude/longitude ranges\n const s = Math.max(sx || 0, sy || 0);\n\n if (s) {\n this.center = this.unproject(new Point(\n sx ? (maxX + minX) / 2 : point.x,\n sy ? (maxY + minY) / 2 : point.y));\n this.zoom += this.scaleZoom(s);\n this._unmodified = unmodified;\n this._constraining = false;\n return;\n }\n\n if (this.latRange) {\n const y = point.y,\n h2 = size.y / 2;\n\n if (y - h2 < minY) y2 = minY + h2;\n if (y + h2 > maxY) y2 = maxY - h2;\n }\n\n if (this.lngRange) {\n const x = point.x,\n w2 = size.x / 2;\n\n if (x - w2 < minX) x2 = minX + w2;\n if (x + w2 > maxX) x2 = maxX - w2;\n }\n\n // pan the map if the screen goes off the range\n if (x2 !== undefined || y2 !== undefined) {\n this.center = this.unproject(new Point(\n x2 !== undefined ? x2 : point.x,\n y2 !== undefined ? y2 : point.y));\n }\n\n this._unmodified = unmodified;\n this._constraining = false;\n }\n\n _calcMatrices() {\n if (!this.height) return;\n\n this.cameraToCenterDistance = 0.5 / Math.tan(this._fov / 2) * this.height;\n\n // Find the distance from the center point [width/2, height/2] to the\n // center top point [width/2, 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 halfFov = this._fov / 2;\n const groundAngle = Math.PI / 2 + this._pitch;\n const topHalfSurfaceDistance = Math.sin(halfFov) * this.cameraToCenterDistance / Math.sin(Math.PI - groundAngle - halfFov);\n const point = this.point;\n const x = point.x, y = point.y;\n\n // Calculate z distance of the farthest fragment that should be rendered.\n const furthestDistance = Math.cos(Math.PI / 2 - this._pitch) * topHalfSurfaceDistance + this.cameraToCenterDistance;\n // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance`\n const farZ = furthestDistance * 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 // Smaller values worked well for mapbox-gl-js but deckgl was encountering precision issues\n // when rendering it's layers using custom layers. This value was experimentally chosen and\n // seems to solve z-fighting issues in deckgl while not clipping buildings too close to the camera.\n const nearZ = this.height / 50;\n\n // matrix for conversion from location to GL coordinates (-1 .. 1)\n let m = new Float64Array(16);\n mat4.perspective(m, this._fov, this.width / this.height, nearZ, farZ);\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 GL coordinates.\n this.mercatorMatrix = mat4.scale([], 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, mercatorZfromAltitude(1, this.center.lat) * this.worldSize, 1]);\n\n this.projMatrix = 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);\n mat4.translate(alignedM, alignedM, [ dx > 0.5 ? dx - 1 : dx, dy > 0.5 ? dy - 1 : dy, 0 ]);\n this.alignedProjMatrix = alignedM;\n\n m = mat4.create();\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.create();\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 // matrix for conversion from location to screen coordinates\n this.pixelMatrix = mat4.multiply(new Float64Array(16), this.labelPlaneMatrix, this.projMatrix);\n\n // inverse matrix for conversion from screen coordinaes to location\n m = mat4.invert(new Float64Array(16), this.pixelMatrix);\n if (!m) throw new Error(\"failed to invert matrix\");\n this.pixelMatrixInverse = m;\n\n this._posMatrixCache = {};\n this._alignedPosMatrixCache = {};\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];\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 *\n * This 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 * - 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 */\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\nexport default Transform;\n","import * as glMatrix from \"./common.js\";\n/**\r\n * 2x2 Matrix\r\n * @module mat2\r\n */\n\n/**\r\n * Creates a new identity mat2\r\n *\r\n * @returns {mat2} a new 2x2 matrix\r\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/**\r\n * Creates a new mat2 initialized with values from an existing matrix\r\n *\r\n * @param {mat2} a matrix to clone\r\n * @returns {mat2} a new 2x2 matrix\r\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/**\r\n * Copy the values from one mat2 to another\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the source matrix\r\n * @returns {mat2} out\r\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/**\r\n * Set a mat2 to the identity matrix\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @returns {mat2} out\r\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/**\r\n * Create a new mat2 with the given values\r\n *\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 2)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 3)\r\n * @returns {mat2} out A new 2x2 matrix\r\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/**\r\n * Set the components of a mat2 to the given values\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 2)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 3)\r\n * @returns {mat2} out\r\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/**\r\n * Transpose the values of a mat2\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the source matrix\r\n * @returns {mat2} out\r\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/**\r\n * Inverts a mat2\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the source matrix\r\n * @returns {mat2} out\r\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/**\r\n * Calculates the adjugate of a mat2\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the source matrix\r\n * @returns {mat2} out\r\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/**\r\n * Calculates the determinant of a mat2\r\n *\r\n * @param {mat2} a the source matrix\r\n * @returns {Number} determinant of a\r\n */\n\nexport function determinant(a) {\n return a[0] * a[3] - a[2] * a[1];\n}\n/**\r\n * Multiplies two mat2's\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the first operand\r\n * @param {mat2} b the second operand\r\n * @returns {mat2} out\r\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/**\r\n * Rotates a mat2 by the given angle\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat2} out\r\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/**\r\n * Scales the mat2 by the dimensions in the given vec2\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the matrix to rotate\r\n * @param {vec2} v the vec2 to scale the matrix by\r\n * @returns {mat2} out\r\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/**\r\n * Creates a matrix from a given angle\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat2.identity(dest);\r\n * mat2.rotate(dest, dest, rad);\r\n *\r\n * @param {mat2} out mat2 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat2} out\r\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/**\r\n * Creates a matrix from a vector scaling\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat2.identity(dest);\r\n * mat2.scale(dest, dest, vec);\r\n *\r\n * @param {mat2} out mat2 receiving operation result\r\n * @param {vec2} v Scaling vector\r\n * @returns {mat2} out\r\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/**\r\n * Returns a string representation of a mat2\r\n *\r\n * @param {mat2} a matrix to represent as a string\r\n * @returns {String} string representation of the matrix\r\n */\n\nexport function str(a) {\n return 'mat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';\n}\n/**\r\n * Returns Frobenius norm of a mat2\r\n *\r\n * @param {mat2} a the matrix to calculate Frobenius norm of\r\n * @returns {Number} Frobenius norm\r\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3]);\n}\n/**\r\n * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix\r\n * @param {mat2} L the lower triangular matrix\r\n * @param {mat2} D the diagonal matrix\r\n * @param {mat2} U the upper triangular matrix\r\n * @param {mat2} a the input matrix to factorize\r\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/**\r\n * Adds two mat2's\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the first operand\r\n * @param {mat2} b the second operand\r\n * @returns {mat2} out\r\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/**\r\n * Subtracts matrix b from matrix a\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the first operand\r\n * @param {mat2} b the second operand\r\n * @returns {mat2} out\r\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/**\r\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {mat2} a The first matrix.\r\n * @param {mat2} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\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/**\r\n * Returns whether or not the matrices have approximately the same elements in the same position.\r\n *\r\n * @param {mat2} a The first matrix.\r\n * @param {mat2} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\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/**\r\n * Multiply each element of the matrix by a scalar.\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the matrix to scale\r\n * @param {Number} b amount to scale the matrix's elements by\r\n * @returns {mat2} out\r\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/**\r\n * Adds two mat2's after multiplying each element of the second operand by a scalar value.\r\n *\r\n * @param {mat2} out the receiving vector\r\n * @param {mat2} a the first operand\r\n * @param {mat2} b the second operand\r\n * @param {Number} scale the amount to scale b's elements by before adding\r\n * @returns {mat2} out\r\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/**\r\n * Alias for {@link mat2.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link mat2.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;","// @flow\n\nimport { bindAll } from '../util/util';\nimport window from '../util/window';\nimport 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 * @returns {Hash} `this`\n */\nclass Hash {\n _map: Map;\n _updateHash: () => ?TimeoutID;\n\n constructor() {\n bindAll([\n '_onHashChange',\n '_updateHash'\n ], this);\n\n // Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds.\n this._updateHash = throttle(this._updateHashUnthrottled.bind(this), 30 * 1000 / 100);\n }\n\n /*\n * Map element to listen for coordinate changes\n *\n * @param {Object} map\n * @returns {Hash} `this`\n */\n addTo(map: Map) {\n this._map = map;\n window.addEventListener('hashchange', this._onHashChange, false);\n this._map.on('moveend', this._updateHash);\n return this;\n }\n\n /*\n * Removes hash\n *\n * @returns {Popup} `this`\n */\n remove() {\n window.removeEventListener('hashchange', this._onHashChange, false);\n this._map.off('moveend', this._updateHash);\n clearTimeout(this._updateHash());\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 return hash;\n }\n\n _onHashChange() {\n const loc = window.location.hash.replace('#', '').split('/');\n if (loc.length >= 3) {\n this._map.jumpTo({\n center: [+loc[2], +loc[1]],\n zoom: +loc[0],\n bearing: +(loc[3] || 0),\n pitch: +(loc[4] || 0)\n });\n return true;\n }\n return false;\n }\n\n _updateHashUnthrottled() {\n const hash = this.getHashString();\n try {\n window.history.replaceState(window.history.state, '', hash);\n } catch (SecurityError) {\n // IE11 does not allow this if the page is within an iframe created\n // with iframe.contentWindow.document.write(...).\n // https://github.com/mapbox/mapbox-gl-js/issues/7410\n }\n }\n\n}\n\nexport default Hash;\n","// @flow strict\n\n/**\n * Throttle the given function to run at most every `period` milliseconds.\n Throttle the given function to run at most every period milliseconds.\n * @private\n */\nexport default function throttle(fn: () => void, time: number): () => ?TimeoutID {\n let pending = false;\n let timerId: ?TimeoutID = null;\n\n const later = () => {\n timerId = null;\n if (pending) {\n fn();\n timerId = setTimeout(later, time);\n pending = false;\n }\n };\n\n return () => {\n pending = true;\n if (!timerId) {\n later();\n }\n return timerId;\n };\n}\n","// @flow\n\nimport { Event } from '../util/evented';\n\nimport DOM from '../util/dom';\nimport Point from '@mapbox/point-geometry';\nimport { extend } from '../util/util';\n\nimport type Map from './map';\nimport type LngLat from '../geo/lng_lat';\n\n/**\n * `MapMouseEvent` is the event type for mouse-related map events.\n * @extends {Object}\n */\nexport class MapMouseEvent extends Event {\n /**\n * The event type.\n */\n type: 'mousedown'\n | 'mouseup'\n | 'click'\n | 'dblclick'\n | 'mousemove'\n | 'mouseover'\n | 'mouseenter'\n | 'mouseleave'\n | 'mouseout'\n | '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 /**\n * @private\n */\n constructor(type: string, map: Map, originalEvent: MouseEvent, data: Object = {}) {\n const point = DOM.mousePos(map.getCanvasContainer(), 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 * @extends {Object}\n */\nexport class MapTouchEvent extends Event {\n /**\n * The event type.\n */\n type: 'touchstart'\n | 'touchend'\n | '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 TouchZoomRotateHandler}\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 /**\n * @private\n */\n constructor(type: string, map: Map, originalEvent: TouchEvent) {\n const points = DOM.touchPos(map.getCanvasContainer(), originalEvent);\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 * @extends {Object}\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 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 * @private\n */\n constructor(type: string, map: Map, originalEvent: WheelEvent) {\n super(type, { originalEvent });\n this._defaultPrevented = false;\n }\n}\n\n/**\n * @typedef {Object} MapBoxZoomEvent\n * @property {MouseEvent} originalEvent\n */\nexport type MapBoxZoomEvent = {\n type: 'boxzoomstart'\n | 'boxzoomend'\n | 'boxzoomcancel',\n map: Map,\n originalEvent: MouseEvent\n};\n\n/**\n * A `MapDataEvent` object is emitted with the {@link Map.event:data}\n * and {@link Map.event: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://www.mapbox.com/mapbox-gl-style-spec/) used by the map\n *\n * @typedef {Object} MapDataEvent\n * @property {string} type The event type.\n * @property {string} dataType The type of data that has changed. One of `'source'`, `'style'`.\n * @property {boolean} [isSourceLoaded] True if the event has a `dataType` of `source` and the source has no outstanding network requests.\n * @property {Object} [source] The [style spec representation of the source](https://www.mapbox.com/mapbox-gl-style-spec/#sources) if the event has a `dataType` of `source`.\n * @property {string} [sourceDataType] Included if the event has a `dataType` of `source` and the event signals\n * that internal data has been received or changed. Possible values are `metadata` and `content`.\n * @property {Object} [tile] 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 * @property {Coordinate} [coord] The coordinate of the tile if the event has a `dataType` of `source` and\n * the event is related to loading of a tile.\n */\nexport type MapDataEvent = {\n type: string,\n dataType: string\n};\n\nexport type MapContextEvent = {\n type: 'webglcontextlost' | 'webglcontextrestored',\n originalEvent: WebGLContextEvent\n}\n\nexport type MapEvent =\n /**\n * Fired when a pointing device (usually a mouse) is pressed within the map.\n *\n * @event mousedown\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n | 'mousedown'\n\n /**\n * Fired when a pointing device (usually a mouse) is released within the map.\n *\n * @event mouseup\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n | 'mouseup'\n\n /**\n * Fired when a pointing device (usually a mouse) is moved within the map.\n *\n * @event mouseover\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)\n * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/)\n * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n */\n | 'mouseover'\n\n /**\n * Fired when a pointing device (usually a mouse) is moved within the map.\n *\n * @event mousemove\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)\n * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/)\n * @see [Display a popup on over](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n */\n | 'mousemove'\n\n /**\n * Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map.\n *\n * @event click\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @see [Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/)\n * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)\n */\n | 'click'\n\n /**\n * Fired when a pointing device (usually a mouse) is clicked twice at the same point on the map.\n *\n * @event dblclick\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n */\n | 'dblclick'\n\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. This event can only be listened for via the three-argument\n * version of {@link Map#on}, where the second argument specifies the desired layer.\n *\n * @event mouseenter\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n */\n | 'mouseenter'\n\n /**\n * Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves\n * the map canvas. This event can only be listened for via the three-argument version of {@link Map#on},\n * where the second argument specifies the desired layer.\n *\n * @event mouseleave\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/)\n */\n | 'mouseleave'\n\n /**\n * Fired when a point device (usually a mouse) leaves the map's canvas.\n *\n * @event mouseout\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n */\n | 'mouseout'\n\n /**\n * Fired when the right button of the mouse is clicked or the context menu key is pressed within the map.\n *\n * @event contextmenu\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n */\n | 'contextmenu'\n\n /**\n * Fired when a [`wheel`](https://developer.mozilla.org/en-US/docs/Web/Events/wheel) event occurs within the map.\n *\n * @event wheel\n * @memberof Map\n * @instance\n * @property {MapWheelEvent} data\n */\n | 'wheel'\n\n /**\n * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the map.\n *\n * @event touchstart\n * @memberof Map\n * @instance\n * @property {MapTouchEvent} data\n */\n | 'touchstart'\n\n /**\n * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the map.\n *\n * @event touchend\n * @memberof Map\n * @instance\n * @property {MapTouchEvent} data\n */\n | 'touchend'\n\n /**\n * Fired when a [`touchmove`](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event occurs within the map.\n *\n * @event touchmove\n * @memberof Map\n * @instance\n * @property {MapTouchEvent} data\n */\n | 'touchmove'\n\n /**\n * Fired when a [`touchcancel`](https://developer.mozilla.org/en-US/docs/Web/Events/touchcancel) event occurs within the map.\n *\n * @event touchcancel\n * @memberof Map\n * @instance\n * @property {MapTouchEvent} data\n */\n | 'touchcancel'\n\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 * @event movestart\n * @memberof Map\n * @instance\n * @property {{originalEvent: DragEvent}} data\n */\n | 'movestart'\n\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 * @event move\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n */\n | 'move'\n\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 * @event moveend\n * @memberof Map\n * @instance\n * @property {{originalEvent: DragEvent}} data\n * @see [Play map locations as a slideshow](https://www.mapbox.com/mapbox-gl-js/example/playback-locations/)\n * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)\n */\n | 'moveend'\n\n /**\n * Fired when a \"drag to pan\" interaction starts. See {@link DragPanHandler}.\n *\n * @event dragstart\n * @memberof Map\n * @instance\n * @property {{originalEvent: DragEvent}} data\n */\n | 'dragstart'\n\n /**\n * Fired repeatedly during a \"drag to pan\" interaction. See {@link DragPanHandler}.\n *\n * @event drag\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n */\n | 'drag'\n\n /**\n * Fired when a \"drag to pan\" interaction ends. See {@link DragPanHandler}.\n *\n * @event dragend\n * @memberof Map\n * @instance\n * @property {{originalEvent: DragEvent}} data\n */\n | 'dragend'\n\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 * @event zoomstart\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n */\n | 'zoomstart'\n\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 * @event zoom\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n * @see [Update a choropleth layer by zoom level](https://www.mapbox.com/mapbox-gl-js/example/updating-choropleth/)\n */\n | 'zoom'\n\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 * @event zoomend\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n */\n | 'zoomend'\n\n /**\n * Fired when a \"drag to rotate\" interaction starts. See {@link DragRotateHandler}.\n *\n * @event rotatestart\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n */\n | 'rotatestart'\n\n /**\n * Fired repeatedly during a \"drag to rotate\" interaction. See {@link DragRotateHandler}.\n *\n * @event rotate\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n */\n | 'rotate'\n\n /**\n * Fired when a \"drag to rotate\" interaction ends. See {@link DragRotateHandler}.\n *\n * @event rotateend\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n */\n | 'rotateend'\n\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 * @event pitchstart\n * @memberof Map\n * @instance\n * @property {MapEventData} data\n */\n | 'pitchstart'\n\n /**\n * Fired whenever the map's pitch (tilt) changes as.\n * the result of either user interaction or methods such as {@link Map#flyTo}.\n *\n * @event pitch\n * @memberof Map\n * @instance\n * @property {MapEventData} data\n */\n | 'pitch'\n\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 * @event pitchend\n * @memberof Map\n * @instance\n * @property {MapEventData} data\n */\n | 'pitchend'\n\n /**\n * Fired when a \"box zoom\" interaction starts. See {@link BoxZoomHandler}.\n *\n * @event boxzoomstart\n * @memberof Map\n * @instance\n * @property {MapBoxZoomEvent} data\n */\n | 'boxzoomstart'\n\n /**\n * Fired when a \"box zoom\" interaction ends. See {@link BoxZoomHandler}.\n *\n * @event boxzoomend\n * @memberof Map\n * @instance\n * @type {Object}\n * @property {MapBoxZoomEvent} data\n */\n | 'boxzoomend'\n\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 * @event boxzoomcancel\n * @memberof Map\n * @instance\n * @property {MapBoxZoomEvent} data\n */\n | 'boxzoomcancel'\n\n /**\n * Fired immediately after the map has been resized.\n *\n * @event resize\n * @memberof Map\n * @instance\n */\n | 'resize'\n\n /**\n * Fired when the WebGL context is lost.\n *\n * @event webglcontextlost\n * @memberof Map\n * @instance\n */\n | 'webglcontextlost'\n\n /**\n * Fired when the WebGL context is restored.\n *\n * @event webglcontextrestored\n * @memberof Map\n * @instance\n */\n | 'webglcontextrestored'\n\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 * @event load\n * @memberof Map\n * @instance\n * @type {Object}\n * @see [Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/)\n * @see [Add live realtime data](https://www.mapbox.com/mapbox-gl-js/example/live-geojson/)\n * @see [Animate a point](https://www.mapbox.com/mapbox-gl-js/example/animate-point-along-line/)\n */\n | 'load'\n\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 * @event render\n * @memberof Map\n * @instance\n */\n | 'render'\n\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 * @event idle\n * @memberof Map\n * @instance\n */\n | 'idle'\n\n /**\n * Fired immediately after the map has been removed with {@link Map.event:remove}.\n *\n * @event remove\n * @memberof Map\n * @instance\n */\n | 'remove'\n\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 * asyncronous operations. If no listeners are bound to the `error` event, the\n * error will be printed to the console.\n *\n * @event error\n * @memberof Map\n * @instance\n * @property {{error: {message: string}}} data\n */\n | 'error'\n\n /**\n * Fired when any map data loads or changes. See {@link MapDataEvent}\n * for more information.\n *\n * @event data\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n */\n | 'data'\n\n /**\n * Fired when the map's style loads or changes. See\n * {@link MapDataEvent} for more information.\n *\n * @event styledata\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n */\n | 'styledata'\n\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. See {@link MapDataEvent} for more information.\n *\n * @event sourcedata\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n */\n | 'sourcedata'\n\n /**\n * Fired when any map data (style, source, tile, etc) begins loading or\n * changing asyncronously. All `dataloading` events are followed by a `data`\n * or `error` event. See {@link MapDataEvent} for more information.\n *\n * @event dataloading\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n */\n | 'dataloading'\n\n /**\n * Fired when the map's style begins loading or changing asyncronously.\n * All `styledataloading` events are followed by a `styledata`\n * or `error` event. See {@link MapDataEvent} for more information.\n *\n * @event styledataloading\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n */\n | 'styledataloading'\n\n /**\n * Fired when one of the map's sources begins loading or changing asyncronously.\n * All `sourcedataloading` events are followed by a `sourcedata` or `error` event.\n * See {@link MapDataEvent} for more information.\n *\n * @event sourcedataloading\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n */\n | 'sourcedataloading'\n\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 *\n * @event styleimagemissing\n * @memberof Map\n * @instance\n * @property {string} id The id of the missing image.\n *\n * @see [Generate and add a missing icon to the map](https://mapbox.com/mapbox-gl-js/example/add-image-missing-generated/)\n */\n | 'styleimagemissing'\n\n /**\n * @event style.load\n * @memberof Map\n * @instance\n * @private\n */\n | 'style.load';\n","// @flow\n\nimport assert from 'assert';\nimport DOM from '../../util/dom';\n\nimport { ease as _ease, bindAll, bezier } from '../../util/util';\nimport browser from '../../util/browser';\nimport window from '../../util/window';\nimport { number as interpolate } from '../../style-spec/util/interpolate';\nimport LngLat from '../../geo/lng_lat';\nimport { Event } from '../../util/evented';\n\nimport type Map from '../map';\nimport type Point from '@mapbox/point-geometry';\nimport type {TaskID} from '../../util/task_queue';\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 */\nclass ScrollZoomHandler {\n _map: Map;\n _el: HTMLElement;\n _enabled: boolean;\n _active: boolean;\n _zooming: boolean;\n _aroundCenter: boolean;\n _around: Point;\n _aroundPoint: Point;\n _type: 'wheel' | 'trackpad' | null;\n _lastValue: number;\n _timeout: ?TimeoutID; // used for delayed-handling of a single wheel movement\n _finishTimeout: ?TimeoutID; // 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: ?((number) => number);\n _prevEase: ?{start: number, duration: number, easing: (number) => number};\n\n _frameId: ?TaskID;\n\n _defaultZoomRate: number;\n _wheelZoomRate: number;\n\n /**\n * @private\n */\n constructor(map: Map) {\n this._map = map;\n this._el = map.getCanvasContainer();\n\n this._delta = 0;\n\n this._defaultZoomRate = defaultZoomRate;\n this._wheelZoomRate = wheelZoomRate;\n\n bindAll([\n '_onWheel',\n '_onTimeout',\n '_onScrollFrame',\n '_onScrollFinished'\n ], this);\n }\n\n /**\n * Set the zoom rate of a trackpad\n * @param {number} [zoomRate = 1/100]\n */\n setZoomRate(zoomRate: number) {\n this._defaultZoomRate = zoomRate;\n }\n\n /**\n * Set the zoom rate of a mouse wheel\n * @param {number} [wheelZoomRate = 1/450]\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 *\n * @returns {boolean} `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;\n }\n\n isZooming() {\n return !!this._zooming;\n }\n /**\n * Enables the \"scroll to zoom\" interaction.\n *\n * @param {Object} [options]\n * @param {string} [options.around] If \"center\" is passed, map will zoom around center of map\n *\n * @example\n * map.scrollZoom.enable();\n * @example\n * map.scrollZoom.enable({ around: 'center' })\n */\n enable(options: any) {\n if (this.isEnabled()) return;\n this._enabled = true;\n this._aroundCenter = options && options.around === 'center';\n }\n\n /**\n * Disables the \"scroll to zoom\" interaction.\n *\n * @example\n * map.scrollZoom.disable();\n */\n disable() {\n if (!this.isEnabled()) return;\n this._enabled = false;\n }\n\n onWheel(e: WheelEvent) {\n if (!this.isEnabled()) return;\n\n // Remove `any` cast when https://github.com/facebook/flow/issues/4879 is fixed.\n let value = e.deltaMode === (window.WheelEvent: any).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 dely 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.isActive()) {\n this._start(e);\n }\n }\n\n e.preventDefault();\n }\n\n _onTimeout(initialEvent: any) {\n this._type = 'wheel';\n this._delta -= this._lastValue;\n if (!this.isActive()) {\n this._start(initialEvent);\n }\n }\n\n _start(e: any) {\n if (!this._delta) return;\n\n if (this._frameId) {\n this._map._cancelRenderFrame(this._frameId);\n this._frameId = null;\n }\n\n this._active = true;\n if (!this.isZooming()) {\n this._zooming = true;\n this._map.fire(new Event('movestart', {originalEvent: e}));\n this._map.fire(new Event('zoomstart', {originalEvent: e}));\n }\n\n if (this._finishTimeout) {\n clearTimeout(this._finishTimeout);\n }\n\n const pos = DOM.mousePos(this._el, e);\n\n this._around = LngLat.convert(this._aroundCenter ? this._map.getCenter() : this._map.unproject(pos));\n this._aroundPoint = this._map.transform.locationPoint(this._around);\n if (!this._frameId) {\n this._frameId = this._map._requestRenderFrame(this._onScrollFrame);\n }\n }\n\n _onScrollFrame() {\n this._frameId = null;\n\n if (!this.isActive()) return;\n const tr = this._map.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 if (this._type === 'wheel' && startZoom && easing) {\n assert(easing && typeof startZoom === 'number');\n\n const t = Math.min((browser.now() - this._lastWheelEventTime) / 200, 1);\n const k = easing(t);\n tr.zoom = interpolate(startZoom, targetZoom, k);\n if (t < 1) {\n if (!this._frameId) {\n this._frameId = this._map._requestRenderFrame(this._onScrollFrame);\n }\n } else {\n finished = true;\n }\n } else {\n tr.zoom = targetZoom;\n finished = true;\n }\n\n tr.setLocationAtPoint(this._around, this._aroundPoint);\n\n this._map.fire(new Event('move', {originalEvent: this._lastWheelEvent}));\n this._map.fire(new Event('zoom', {originalEvent: this._lastWheelEvent}));\n\n if (finished) {\n this._active = false;\n this._finishTimeout = setTimeout(() => {\n this._zooming = false;\n this._map.fire(new Event('zoomend', {originalEvent: this._lastWheelEvent}));\n this._map.fire(new Event('moveend', {originalEvent: this._lastWheelEvent}));\n delete this._targetZoom;\n }, 200);\n }\n }\n\n _smoothOutEasing(duration: number) {\n let easing = _ease;\n\n if (this._prevEase) {\n const ease = this._prevEase,\n t = (browser.now() - ease.start) / ease.duration,\n speed = ease.easing(t + 0.01) - ease.easing(t),\n\n // Quick hack to make new bezier that is continuous with last\n x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01,\n 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\nexport default ScrollZoomHandler;\n","// @flow\n\nimport DOM from '../../util/dom';\n\nimport { bindAll } from '../../util/util';\nimport window from '../../util/window';\nimport { Event } from '../../util/evented';\n\nimport type Map from '../map';\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 */\nclass BoxZoomHandler {\n _map: Map;\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 /**\n * @private\n */\n constructor(map: Map, options: {\n clickTolerance?: number\n }) {\n this._map = map;\n this._el = map.getCanvasContainer();\n this._container = map.getContainer();\n this._clickTolerance = options.clickTolerance || 1;\n\n bindAll([\n '_onMouseMove',\n '_onMouseUp',\n '_onKeyDown'\n ], this);\n }\n\n /**\n * Returns a Boolean indicating whether the \"box zoom\" interaction is enabled.\n *\n * @returns {boolean} `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 {boolean} `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 * map.boxZoom.enable();\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 * map.boxZoom.disable();\n */\n disable() {\n if (!this.isEnabled()) return;\n this._enabled = false;\n }\n\n onMouseDown(e: MouseEvent) {\n if (!this.isEnabled()) return;\n if (!(e.shiftKey && e.button === 0)) return;\n\n window.document.addEventListener('mousemove', this._onMouseMove, false);\n window.document.addEventListener('keydown', this._onKeyDown, false);\n window.document.addEventListener('mouseup', this._onMouseUp, false);\n\n DOM.disableDrag();\n this._startPos = this._lastPos = DOM.mousePos(this._el, e);\n this._active = true;\n }\n\n _onMouseMove(e: MouseEvent) {\n const pos = DOM.mousePos(this._el, e);\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', 'mapboxgl-boxzoom', this._container);\n this._container.classList.add('mapboxgl-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 _onMouseUp(e: MouseEvent) {\n if (e.button !== 0) return;\n\n const p0 = this._startPos,\n p1 = DOM.mousePos(this._el, e);\n\n this._finish();\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\n .fitScreenCoordinates(p0, p1, this._map.getBearing(), {linear: true})\n .fire(new Event('boxzoomend', { originalEvent: e}));\n }\n }\n\n _onKeyDown(e: KeyboardEvent) {\n if (e.keyCode === 27) {\n this._finish();\n this._fireEvent('boxzoomcancel', e);\n }\n }\n\n _finish() {\n this._active = false;\n\n window.document.removeEventListener('mousemove', this._onMouseMove, false);\n window.document.removeEventListener('keydown', this._onKeyDown, false);\n window.document.removeEventListener('mouseup', this._onMouseUp, false);\n\n this._container.classList.remove('mapboxgl-crosshair');\n\n if (this._box) {\n DOM.remove(this._box);\n this._box = (null: any);\n }\n\n DOM.enableDrag();\n\n delete this._startPos;\n delete this._lastPos;\n }\n\n _fireEvent(type: string, e: *) {\n return this._map.fire(new Event(type, { originalEvent: e }));\n }\n}\n\nexport default BoxZoomHandler;\n","// @flow\n\nimport DOM from '../../util/dom';\n\nimport { bezier, bindAll } from '../../util/util';\nimport window from '../../util/window';\nimport browser from '../../util/browser';\nimport { Event } from '../../util/evented';\nimport assert from 'assert';\n\nimport type Map from '../map';\nimport type Point from '@mapbox/point-geometry';\nimport type {TaskID} from '../../util/task_queue';\n\nconst inertiaLinearity = 0.25,\n inertiaEasing = bezier(0, 0, inertiaLinearity, 1),\n inertiaMaxSpeed = 180, // deg/s\n inertiaDeceleration = 720; // deg/s^2\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 */\nclass DragRotateHandler {\n _map: Map;\n _el: HTMLElement;\n _state: 'disabled' | 'enabled' | 'pending' | 'active';\n _button: 'right' | 'left';\n _eventButton: number;\n _bearingSnap: number;\n _pitchWithRotate: boolean;\n\n _startPos: Point;\n _prevPos: Point;\n _lastPos: Point;\n _startTime: number;\n _lastMoveEvent: MouseEvent;\n _inertia: Array<[number, number]>;\n _center: Point;\n _frameId: ?TaskID;\n\n /**\n * @param {Map} map The Mapbox GL JS map to add the handler to.\n * @param {Object} [options]\n * @param {number} [options.bearingSnap] The threshold, measured in degrees, that determines when the map's\n * bearing will snap to north.\n * @param {bool} [options.pitchWithRotate=true] Control the map pitch in addition to the bearing\n * @private\n */\n constructor(map: Map, options: {\n button?: 'right' | 'left',\n element?: HTMLElement,\n bearingSnap?: number,\n pitchWithRotate?: boolean\n }) {\n this._map = map;\n this._el = options.element || map.getCanvasContainer();\n this._state = 'disabled';\n this._button = options.button || 'right';\n this._bearingSnap = options.bearingSnap || 0;\n this._pitchWithRotate = options.pitchWithRotate !== false;\n\n bindAll([\n 'onMouseDown',\n '_onMouseMove',\n '_onMouseUp',\n '_onBlur',\n '_onDragFrame'\n ], this);\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to rotate\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"drag to rotate\" interaction is enabled.\n */\n isEnabled() {\n return this._state !== 'disabled';\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to rotate\" interaction is active, i.e. currently being used.\n *\n * @returns {boolean} `true` if the \"drag to rotate\" interaction is active.\n */\n isActive() {\n return this._state === 'active';\n }\n\n /**\n * Enables the \"drag to rotate\" interaction.\n *\n * @example\n * map.dragRotate.enable();\n */\n enable() {\n if (this.isEnabled()) return;\n this._state = 'enabled';\n }\n\n /**\n * Disables the \"drag to rotate\" interaction.\n *\n * @example\n * map.dragRotate.disable();\n */\n disable() {\n if (!this.isEnabled()) return;\n switch (this._state) {\n case 'active':\n this._state = 'disabled';\n this._unbind();\n this._deactivate();\n this._fireEvent('rotateend');\n if (this._pitchWithRotate) {\n this._fireEvent('pitchend');\n }\n this._fireEvent('moveend');\n break;\n case 'pending':\n this._state = 'disabled';\n this._unbind();\n break;\n default:\n this._state = 'disabled';\n break;\n }\n }\n\n onMouseDown(e: MouseEvent) {\n if (this._state !== 'enabled') return;\n\n const touchEvent = e.type === 'touchstart';\n\n if (touchEvent) {\n this._startTime = Date.now();\n } else {\n if (this._button === 'right') {\n this._eventButton = DOM.mouseButton(e);\n if (this._eventButton !== (e.ctrlKey ? 0 : 2)) return;\n } else {\n if (e.ctrlKey || DOM.mouseButton(e) !== 0) return;\n this._eventButton = 0;\n }\n }\n\n DOM.disableDrag();\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 if (touchEvent) {\n window.document.addEventListener('touchmove', this._onMouseMove, { capture: true });\n window.document.addEventListener('touchend', this._onMouseUp);\n } else {\n window.document.addEventListener('mousemove', this._onMouseMove, { capture: true });\n window.document.addEventListener('mouseup', this._onMouseUp);\n }\n\n // Deactivate when the window loses focus. Otherwise if a mouseup occurs when the window\n // isn't in focus, dragging will continue even though the mouse is no longer pressed.\n window.addEventListener('blur', this._onBlur);\n\n this._state = 'pending';\n this._inertia = [[browser.now(), this._map.getBearing()]];\n this._startPos = this._prevPos = this._lastPos = DOM.mousePos(this._el, e);\n this._center = this._map.transform.centerPoint; // Center of rotation\n\n e.preventDefault();\n }\n\n _onMouseMove(e: MouseEvent) {\n const pos = DOM.mousePos(this._el, e);\n if (this._lastPos.equals(pos)) {\n return;\n }\n\n this._lastMoveEvent = e;\n this._lastPos = pos;\n\n if (this._state === 'pending') {\n this._state = 'active';\n this._fireEvent('rotatestart', e);\n this._fireEvent('movestart', e);\n if (this._pitchWithRotate) {\n this._fireEvent('pitchstart', e);\n }\n }\n\n if (!this._frameId) {\n this._frameId = this._map._requestRenderFrame(this._onDragFrame);\n }\n }\n\n _onDragFrame() {\n this._frameId = null;\n\n const e = this._lastMoveEvent;\n if (!e) return;\n const tr = this._map.transform;\n\n const p1 = this._prevPos,\n p2 = this._lastPos,\n bearingDiff = (p1.x - p2.x) * 0.8,\n pitchDiff = (p1.y - p2.y) * -0.5,\n bearing = tr.bearing - bearingDiff,\n pitch = tr.pitch - pitchDiff,\n inertia = this._inertia,\n last = inertia[inertia.length - 1];\n\n this._drainInertiaBuffer();\n inertia.push([browser.now(), this._map._normalizeBearing(bearing, last[1])]);\n\n tr.bearing = bearing;\n if (this._pitchWithRotate) {\n this._fireEvent('pitch', e);\n tr.pitch = pitch;\n }\n\n this._fireEvent('rotate', e);\n this._fireEvent('move', e);\n\n delete this._lastMoveEvent;\n this._prevPos = this._lastPos;\n }\n\n _onMouseUp(e: MouseEvent) {\n const touchEvent = e.type === 'touchend';\n\n if (touchEvent && (this._startPos === this._lastPos) && (Date.now() - this._startTime) < 300) {\n this._el.click();\n }\n\n if (DOM.mouseButton(e) !== this._eventButton) return;\n switch (this._state) {\n case 'active':\n this._state = 'enabled';\n DOM.suppressClick();\n this._unbind();\n this._deactivate();\n this._inertialRotate(e);\n break;\n case 'pending':\n this._state = 'enabled';\n this._unbind();\n break;\n default:\n assert(false);\n break;\n }\n }\n\n _onBlur(e: FocusEvent) {\n switch (this._state) {\n case 'active':\n this._state = 'enabled';\n this._unbind();\n this._deactivate();\n this._fireEvent('rotateend', e);\n if (this._pitchWithRotate) {\n this._fireEvent('pitchend', e);\n }\n this._fireEvent('moveend', e);\n break;\n case 'pending':\n this._state = 'enabled';\n this._unbind();\n break;\n default:\n assert(false);\n break;\n }\n }\n\n _unbind() {\n window.document.removeEventListener('mousemove', this._onMouseMove, { capture: true });\n window.document.removeEventListener('mouseup', this._onMouseUp);\n window.document.removeEventListener('touchmove', this._onMouseMove, { capture: true });\n window.document.removeEventListener('touchend', this._onMouseUp);\n window.removeEventListener('blur', this._onBlur);\n DOM.enableDrag();\n }\n\n _deactivate() {\n if (this._frameId) {\n this._map._cancelRenderFrame(this._frameId);\n this._frameId = null;\n }\n delete this._lastMoveEvent;\n delete this._startPos;\n delete this._prevPos;\n delete this._lastPos;\n }\n\n _inertialRotate(e: MouseEvent) {\n this._fireEvent('rotateend', e);\n this._drainInertiaBuffer();\n\n const map = this._map,\n mapBearing = map.getBearing(),\n inertia = this._inertia;\n\n const finish = () => {\n if (Math.abs(mapBearing) < this._bearingSnap) {\n map.resetNorth({noMoveStart: true}, { originalEvent: e });\n } else {\n this._fireEvent('moveend', e);\n }\n if (this._pitchWithRotate) this._fireEvent('pitchend', e);\n };\n\n if (inertia.length < 2) {\n finish();\n return;\n }\n\n const first = inertia[0],\n last = inertia[inertia.length - 1],\n previous = inertia[inertia.length - 2];\n let bearing = map._normalizeBearing(mapBearing, previous[1]);\n const flingDiff = last[1] - first[1],\n sign = flingDiff < 0 ? -1 : 1,\n flingDuration = (last[0] - first[0]) / 1000;\n\n if (flingDiff === 0 || flingDuration === 0) {\n finish();\n return;\n }\n\n let speed = Math.abs(flingDiff * (inertiaLinearity / flingDuration)); // deg/s\n if (speed > inertiaMaxSpeed) {\n speed = inertiaMaxSpeed;\n }\n\n const duration = speed / (inertiaDeceleration * inertiaLinearity),\n offset = sign * speed * (duration / 2);\n\n bearing += offset;\n\n if (Math.abs(map._normalizeBearing(bearing, 0)) < this._bearingSnap) {\n bearing = map._normalizeBearing(0, bearing);\n }\n\n map.rotateTo(bearing, {\n duration: duration * 1000,\n easing: inertiaEasing,\n noMoveStart: true\n }, { originalEvent: e });\n }\n\n _fireEvent(type: string, e: *) {\n return this._map.fire(new Event(type, e ? { originalEvent: e } : {}));\n }\n\n _drainInertiaBuffer() {\n const inertia = this._inertia,\n now = browser.now(),\n cutoff = 160; //msec\n\n while (inertia.length > 0 && now - inertia[0][0] > cutoff)\n inertia.shift();\n }\n}\n\nexport default DragRotateHandler;\n","// @flow\n\nimport DOM from '../../util/dom';\nimport { bezier, bindAll } from '../../util/util';\nimport window from '../../util/window';\nimport browser from '../../util/browser';\nimport { Event } from '../../util/evented';\nimport assert from 'assert';\n\nimport type Map from '../map';\nimport type Point from '@mapbox/point-geometry';\nimport type {TaskID} from '../../util/task_queue';\n\nconst inertiaLinearity = 0.3,\n inertiaEasing = bezier(0, 0, inertiaLinearity, 1),\n inertiaMaxSpeed = 1400, // px/s\n inertiaDeceleration = 2500; // px/s^2\n\n/**\n * The `DragPanHandler` allows the user to pan the map by clicking and dragging\n * the cursor.\n */\nclass DragPanHandler {\n _map: Map;\n _el: HTMLElement;\n _state: 'disabled' | 'enabled' | 'pending' | 'active';\n _startPos: Point;\n _mouseDownPos: Point;\n _prevPos: Point;\n _lastPos: Point;\n _lastMoveEvent: MouseEvent | TouchEvent | void;\n _inertia: Array<[number, Point]>;\n _frameId: ?TaskID;\n _clickTolerance: number;\n\n /**\n * @private\n */\n constructor(map: Map, options: {\n clickTolerance?: number\n }) {\n this._map = map;\n this._el = map.getCanvasContainer();\n this._state = 'disabled';\n this._clickTolerance = options.clickTolerance || 1;\n\n bindAll([\n '_onMove',\n '_onMouseUp',\n '_onTouchEnd',\n '_onBlur',\n '_onDragFrame'\n ], this);\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to pan\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"drag to pan\" interaction is enabled.\n */\n isEnabled() {\n return this._state !== 'disabled';\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to pan\" interaction is active, i.e. currently being used.\n *\n * @returns {boolean} `true` if the \"drag to pan\" interaction is active.\n */\n isActive() {\n return this._state === 'active';\n }\n\n /**\n * Enables the \"drag to pan\" interaction.\n *\n * @example\n * map.dragPan.enable();\n */\n enable() {\n if (this.isEnabled()) return;\n this._el.classList.add('mapboxgl-touch-drag-pan');\n this._state = 'enabled';\n }\n\n /**\n * Disables the \"drag to pan\" interaction.\n *\n * @example\n * map.dragPan.disable();\n */\n disable() {\n if (!this.isEnabled()) return;\n this._el.classList.remove('mapboxgl-touch-drag-pan');\n switch (this._state) {\n case 'active':\n this._state = 'disabled';\n this._unbind();\n this._deactivate();\n this._fireEvent('dragend');\n this._fireEvent('moveend');\n break;\n case 'pending':\n this._state = 'disabled';\n this._unbind();\n break;\n default:\n this._state = 'disabled';\n break;\n }\n }\n\n onMouseDown(e: MouseEvent) {\n if (this._state !== 'enabled') return;\n if (e.ctrlKey || DOM.mouseButton(e) !== 0) return;\n\n // Bind window-level event listeners for mousemove/up 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 DOM.addEventListener(window.document, 'mousemove', this._onMove, {capture: true});\n DOM.addEventListener(window.document, 'mouseup', this._onMouseUp);\n\n this._start(e);\n }\n\n onTouchStart(e: TouchEvent) {\n if (this._state !== 'enabled') return;\n if (e.touches.length > 1) return;\n\n // Bind window-level event listeners for touchmove/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 DOM.addEventListener(window.document, 'touchmove', this._onMove, {capture: true, passive: false});\n DOM.addEventListener(window.document, 'touchend', this._onTouchEnd);\n\n this._start(e);\n }\n\n _start(e: MouseEvent | TouchEvent) {\n // Deactivate when the window loses focus. Otherwise if a mouseup occurs when the window\n // isn't in focus, dragging will continue even though the mouse is no longer pressed.\n window.addEventListener('blur', this._onBlur);\n\n this._state = 'pending';\n this._startPos = this._mouseDownPos = this._prevPos = this._lastPos = DOM.mousePos(this._el, e);\n this._inertia = [[browser.now(), this._startPos]];\n }\n\n _onMove(e: MouseEvent | TouchEvent) {\n e.preventDefault();\n\n const pos = DOM.mousePos(this._el, e);\n if (this._lastPos.equals(pos) || (this._state === 'pending' && pos.dist(this._mouseDownPos) < this._clickTolerance)) {\n return;\n }\n\n this._lastMoveEvent = e;\n this._lastPos = pos;\n this._drainInertiaBuffer();\n this._inertia.push([browser.now(), this._lastPos]);\n\n if (this._state === 'pending') {\n // we treat the first move event (rather than the mousedown event)\n // as the start of the drag\n this._state = 'active';\n this._fireEvent('dragstart', e);\n this._fireEvent('movestart', e);\n }\n\n if (!this._frameId) {\n this._frameId = this._map._requestRenderFrame(this._onDragFrame);\n }\n }\n\n /**\n * Called in each render frame while dragging is happening.\n * @private\n */\n _onDragFrame() {\n this._frameId = null;\n\n const e = this._lastMoveEvent;\n if (!e) return;\n const tr = this._map.transform;\n tr.setLocationAtPoint(tr.pointLocation(this._prevPos), this._lastPos);\n this._fireEvent('drag', e);\n this._fireEvent('move', e);\n\n this._prevPos = this._lastPos;\n delete this._lastMoveEvent;\n }\n\n _onMouseUp(e: MouseEvent) {\n if (DOM.mouseButton(e) !== 0) return;\n switch (this._state) {\n case 'active':\n this._state = 'enabled';\n DOM.suppressClick();\n this._unbind();\n this._deactivate();\n this._inertialPan(e);\n break;\n case 'pending':\n this._state = 'enabled';\n this._unbind();\n break;\n default:\n assert(false);\n break;\n }\n }\n\n _onTouchEnd(e: TouchEvent) {\n switch (this._state) {\n case 'active':\n this._state = 'enabled';\n this._unbind();\n this._deactivate();\n this._inertialPan(e);\n break;\n case 'pending':\n this._state = 'enabled';\n this._unbind();\n break;\n default:\n assert(false);\n break;\n }\n }\n\n _onBlur(e: FocusEvent) {\n switch (this._state) {\n case 'active':\n this._state = 'enabled';\n this._unbind();\n this._deactivate();\n this._fireEvent('dragend', e);\n this._fireEvent('moveend', e);\n break;\n case 'pending':\n this._state = 'enabled';\n this._unbind();\n break;\n default:\n assert(false);\n break;\n }\n }\n\n _unbind() {\n DOM.removeEventListener(window.document, 'touchmove', this._onMove, {capture: true, passive: false});\n DOM.removeEventListener(window.document, 'touchend', this._onTouchEnd);\n DOM.removeEventListener(window.document, 'mousemove', this._onMove, {capture: true});\n DOM.removeEventListener(window.document, 'mouseup', this._onMouseUp);\n DOM.removeEventListener(window, 'blur', this._onBlur);\n }\n\n _deactivate() {\n if (this._frameId) {\n this._map._cancelRenderFrame(this._frameId);\n this._frameId = null;\n }\n delete this._lastMoveEvent;\n delete this._startPos;\n delete this._prevPos;\n delete this._mouseDownPos;\n delete this._lastPos;\n }\n\n _inertialPan(e: MouseEvent | TouchEvent) {\n this._fireEvent('dragend', e);\n\n this._drainInertiaBuffer();\n const inertia = this._inertia;\n if (inertia.length < 2) {\n this._fireEvent('moveend', e);\n return;\n }\n\n const last = inertia[inertia.length - 1],\n first = inertia[0],\n flingOffset = last[1].sub(first[1]),\n flingDuration = (last[0] - first[0]) / 1000;\n\n if (flingDuration === 0 || last[1].equals(first[1])) {\n this._fireEvent('moveend', e);\n return;\n }\n\n // calculate px/s velocity & adjust for increased initial animation speed when easing out\n const velocity = flingOffset.mult(inertiaLinearity / flingDuration);\n let speed = velocity.mag(); // px/s\n\n if (speed > inertiaMaxSpeed) {\n speed = inertiaMaxSpeed;\n velocity._unit()._mult(speed);\n }\n\n const duration = speed / (inertiaDeceleration * inertiaLinearity),\n offset = velocity.mult(-duration / 2);\n\n this._map.panBy(offset, {\n duration: duration * 1000,\n easing: inertiaEasing,\n noMoveStart: true\n }, { originalEvent: e });\n }\n\n _fireEvent(type: string, e: *) {\n return this._map.fire(new Event(type, e ? { originalEvent: e } : {}));\n }\n\n _drainInertiaBuffer() {\n const inertia = this._inertia,\n now = browser.now(),\n cutoff = 160; // msec\n\n while (inertia.length > 0 && now - inertia[0][0] > cutoff) inertia.shift();\n }\n}\n\nexport default DragPanHandler;\n","// @flow\n\nimport { bindAll } from '../../util/util';\n\nimport type Map from '../map';\n\nconst panStep = 100,\n bearingStep = 15,\n pitchStep = 10;\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 */\nclass KeyboardHandler {\n _map: Map;\n _el: HTMLElement;\n _enabled: boolean;\n\n /**\n * @private\n */\n constructor(map: Map) {\n this._map = map;\n this._el = map.getCanvasContainer();\n\n bindAll([\n '_onKeyDown'\n ], this);\n }\n\n /**\n * Returns a Boolean indicating whether keyboard interaction is enabled.\n *\n * @returns {boolean} `true` if keyboard interaction is enabled.\n */\n isEnabled() {\n return !!this._enabled;\n }\n\n /**\n * Enables keyboard interaction.\n *\n * @example\n * map.keyboard.enable();\n */\n enable() {\n if (this.isEnabled()) return;\n this._el.addEventListener('keydown', this._onKeyDown, false);\n this._enabled = true;\n }\n\n /**\n * Disables keyboard interaction.\n *\n * @example\n * map.keyboard.disable();\n */\n disable() {\n if (!this.isEnabled()) return;\n this._el.removeEventListener('keydown', this._onKeyDown);\n this._enabled = false;\n }\n\n _onKeyDown(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 yDir = 1;\n e.preventDefault();\n }\n break;\n\n default:\n return;\n }\n\n const map = this._map;\n const zoom = map.getZoom();\n\n const easeOptions = {\n duration: 300,\n delayEndEvents: 500,\n easing: easeOut,\n\n zoom: zoomDir ? Math.round(zoom) + zoomDir * (e.shiftKey ? 2 : 1) : zoom,\n bearing: map.getBearing() + bearingDir * bearingStep,\n pitch: map.getPitch() + pitchDir * pitchStep,\n offset: [-xDir * panStep, -yDir * panStep],\n center: map.getCenter()\n };\n\n map.easeTo(easeOptions, {originalEvent: e});\n }\n}\n\nfunction easeOut(t) {\n return t * (2 - t);\n}\n\nexport default KeyboardHandler;\n","// @flow\n\nimport { bindAll } from '../../util/util';\n\nimport type Map from '../map';\nimport type {MapMouseEvent, MapTouchEvent} from '../events';\nimport type Point from '@mapbox/point-geometry';\n\n// maximum distance between two tap Points for them to qualify as a double-tap\nconst maxDist = 30;\n\n/**\n * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by\n * double clicking or double tapping.\n */\nclass DoubleClickZoomHandler {\n _map: Map;\n _enabled: boolean;\n _active: boolean;\n _tapped: ?TimeoutID;\n _tappedPoint: ?Point;\n\n /**\n * @private\n */\n constructor(map: Map) {\n this._map = map;\n\n bindAll([\n '_onDblClick',\n '_onZoomEnd'\n ], this);\n }\n\n /**\n * Returns a Boolean indicating whether the \"double click to zoom\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"double click to zoom\" interaction is enabled.\n */\n isEnabled() {\n return !!this._enabled;\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 {boolean} `true` if the \"double click to zoom\" interaction is active.\n */\n isActive() {\n return !!this._active;\n }\n\n /**\n * Enables the \"double click to zoom\" interaction.\n *\n * @example\n * map.doubleClickZoom.enable();\n */\n enable() {\n if (this.isEnabled()) return;\n this._enabled = true;\n }\n\n /**\n * Disables the \"double click to zoom\" interaction.\n *\n * @example\n * map.doubleClickZoom.disable();\n */\n disable() {\n if (!this.isEnabled()) return;\n this._enabled = false;\n }\n\n onTouchStart(e: MapTouchEvent) {\n if (!this.isEnabled()) return;\n if (e.points.length > 1) return;\n\n if (!this._tapped) {\n this._tappedPoint = e.points[0];\n this._tapped = setTimeout(() => { this._tapped = null; this._tappedPoint = null; }, 300);\n } else {\n const newTap = e.points[0];\n const firstTap = this._tappedPoint;\n\n if (firstTap && firstTap.dist(newTap) <= maxDist) {\n e.originalEvent.preventDefault(); // prevent duplicate zoom on dblclick\n\n const onTouchEnd = () => { // ignore the touchend event, as it has no point we can zoom to\n if (this._tapped) { // make sure we are still within the timeout window\n this._zoom(e); // pass the original touchstart event, with the tapped point\n }\n this._map.off('touchcancel', onTouchCancel);\n this._resetTapped();\n };\n\n const onTouchCancel = () => {\n this._map.off('touchend', onTouchEnd);\n this._resetTapped();\n };\n\n this._map.once('touchend', onTouchEnd);\n this._map.once('touchcancel', onTouchCancel);\n\n } else { // touches are too far apart, don't zoom\n this._resetTapped();\n }\n }\n }\n\n _resetTapped() {\n clearTimeout(this._tapped);\n this._tapped = null;\n this._tappedPoint = null;\n }\n\n onDblClick(e: MapMouseEvent) {\n if (!this.isEnabled()) return;\n e.originalEvent.preventDefault();\n this._zoom(e);\n }\n\n _zoom(e: MapMouseEvent | MapTouchEvent) {\n this._active = true;\n this._map.on('zoomend', this._onZoomEnd);\n this._map.zoomTo(\n this._map.getZoom() + (e.originalEvent.shiftKey ? -1 : 1),\n {around: e.lngLat},\n e\n );\n }\n\n _onZoomEnd() {\n this._active = false;\n this._map.off('zoomend', this._onZoomEnd);\n }\n}\n\nexport default DoubleClickZoomHandler;\n","// @flow\n\nimport DOM from '../../util/dom';\nimport { bezier, bindAll } from '../../util/util';\nimport window from '../../util/window';\nimport browser from '../../util/browser';\nimport { Event } from '../../util/evented';\n\nimport type Map from '../map';\nimport type Point from '@mapbox/point-geometry';\nimport type LngLat from '../../geo/lng_lat';\nimport type {TaskID} from '../../util/task_queue';\n\nconst inertiaLinearity = 0.15,\n inertiaEasing = bezier(0, 0, inertiaLinearity, 1),\n inertiaDeceleration = 12, // scale / s^2\n inertiaMaxSpeed = 2.5, // scale / s\n significantScaleThreshold = 0.15,\n significantRotateThreshold = 10;\n\n/**\n * The `TouchZoomRotateHandler` allows the user to zoom and rotate the map by\n * pinching on a touchscreen.\n */\nclass TouchZoomRotateHandler {\n _map: Map;\n _el: HTMLElement;\n _enabled: boolean;\n _aroundCenter: boolean;\n _rotationDisabled: boolean;\n _startVec: Point;\n _startAround: LngLat;\n _startScale: number;\n _startBearing: number;\n _gestureIntent: 'rotate' | 'zoom' | void;\n _inertia: Array<[number, number, Point]>;\n _lastTouchEvent: TouchEvent;\n _frameId: ?TaskID;\n\n /**\n * @private\n */\n constructor(map: Map) {\n this._map = map;\n this._el = map.getCanvasContainer();\n\n bindAll([\n '_onMove',\n '_onEnd',\n '_onTouchFrame'\n ], this);\n }\n\n /**\n * Returns a Boolean indicating whether the \"pinch to rotate and zoom\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"pinch to rotate and zoom\" interaction is enabled.\n */\n isEnabled() {\n return !!this._enabled;\n }\n\n /**\n * Enables the \"pinch to rotate and zoom\" interaction.\n *\n * @param {Object} [options]\n * @param {string} [options.around] If \"center\" is passed, map will zoom around the center\n *\n * @example\n * map.touchZoomRotate.enable();\n * @example\n * map.touchZoomRotate.enable({ around: 'center' });\n */\n enable(options: ?{around?: 'center'}) {\n if (this.isEnabled()) return;\n this._el.classList.add('mapboxgl-touch-zoom-rotate');\n this._enabled = true;\n this._aroundCenter = !!options && options.around === 'center';\n }\n\n /**\n * Disables the \"pinch to rotate and zoom\" interaction.\n *\n * @example\n * map.touchZoomRotate.disable();\n */\n disable() {\n if (!this.isEnabled()) return;\n this._el.classList.remove('mapboxgl-touch-zoom-rotate');\n this._enabled = false;\n }\n\n /**\n * Disables the \"pinch to rotate\" interaction, leaving the \"pinch to zoom\"\n * interaction enabled.\n *\n * @example\n * map.touchZoomRotate.disableRotation();\n */\n disableRotation() {\n this._rotationDisabled = true;\n }\n\n /**\n * Enables the \"pinch to rotate\" interaction.\n *\n * @example\n * map.touchZoomRotate.enable();\n * map.touchZoomRotate.enableRotation();\n */\n enableRotation() {\n this._rotationDisabled = false;\n }\n\n onStart(e: TouchEvent) {\n if (!this.isEnabled()) return;\n if (e.touches.length !== 2) return;\n\n const p0 = DOM.mousePos(this._el, e.touches[0]),\n p1 = DOM.mousePos(this._el, e.touches[1]),\n center = p0.add(p1).div(2);\n\n this._startVec = p0.sub(p1);\n this._startAround = this._map.transform.pointLocation(center);\n this._gestureIntent = undefined;\n this._inertia = [];\n\n DOM.addEventListener(window.document, 'touchmove', this._onMove, {passive: false});\n DOM.addEventListener(window.document, 'touchend', this._onEnd);\n }\n\n _getTouchEventData(e: TouchEvent) {\n const p0 = DOM.mousePos(this._el, e.touches[0]),\n p1 = DOM.mousePos(this._el, e.touches[1]);\n\n const vec = p0.sub(p1);\n return {\n vec,\n center: p0.add(p1).div(2),\n scale: vec.mag() / this._startVec.mag(),\n bearing: this._rotationDisabled ? 0 : vec.angleWith(this._startVec) * 180 / Math.PI\n };\n }\n\n _onMove(e: TouchEvent) {\n if (e.touches.length !== 2) return;\n\n const {vec, scale, bearing} = this._getTouchEventData(e);\n\n // Determine 'intent' by whichever threshold is surpassed first,\n // then keep that state for the duration of this gesture.\n if (!this._gestureIntent) {\n // when rotation is disabled, any scale change triggers the zoom gesture to start\n const scalingSignificantly = (this._rotationDisabled && scale !== 1) || (Math.abs(1 - scale) > significantScaleThreshold),\n rotatingSignificantly = (Math.abs(bearing) > significantRotateThreshold);\n\n if (rotatingSignificantly) {\n this._gestureIntent = 'rotate';\n } else if (scalingSignificantly) {\n this._gestureIntent = 'zoom';\n }\n\n if (this._gestureIntent) {\n this._map.fire(new Event(`${this._gestureIntent}start`, { originalEvent: e }));\n this._map.fire(new Event('movestart', { originalEvent: e }));\n this._startVec = vec;\n }\n }\n\n this._lastTouchEvent = e;\n if (!this._frameId) {\n this._frameId = this._map._requestRenderFrame(this._onTouchFrame);\n }\n\n e.preventDefault();\n }\n\n _onTouchFrame() {\n this._frameId = null;\n\n const gestureIntent = this._gestureIntent;\n if (!gestureIntent) return;\n\n const tr = this._map.transform;\n\n if (!this._startScale) {\n this._startScale = tr.scale;\n this._startBearing = tr.bearing;\n }\n\n const {center, bearing, scale} = this._getTouchEventData(this._lastTouchEvent);\n const around = tr.pointLocation(center);\n const aroundPoint = tr.locationPoint(around);\n\n if (gestureIntent === 'rotate') {\n tr.bearing = this._startBearing + bearing;\n }\n\n tr.zoom = tr.scaleZoom(this._startScale * scale);\n\n tr.setLocationAtPoint(this._startAround, aroundPoint);\n\n this._map.fire(new Event(gestureIntent, {originalEvent: this._lastTouchEvent}));\n this._map.fire(new Event('move', {originalEvent: this._lastTouchEvent}));\n\n this._drainInertiaBuffer();\n this._inertia.push([browser.now(), scale, center]);\n }\n\n _onEnd(e: TouchEvent) {\n DOM.removeEventListener(window.document, 'touchmove', this._onMove, {passive: false});\n DOM.removeEventListener(window.document, 'touchend', this._onEnd);\n\n const gestureIntent = this._gestureIntent;\n const startScale = this._startScale;\n\n if (this._frameId) {\n this._map._cancelRenderFrame(this._frameId);\n this._frameId = null;\n }\n delete this._gestureIntent;\n delete this._startScale;\n delete this._startBearing;\n delete this._lastTouchEvent;\n\n if (!gestureIntent) return;\n\n this._map.fire(new Event(`${gestureIntent}end`, { originalEvent: e }));\n\n this._drainInertiaBuffer();\n\n const inertia = this._inertia,\n map = this._map;\n\n if (inertia.length < 2) {\n map.snapToNorth({}, { originalEvent: e });\n return;\n }\n\n const last = inertia[inertia.length - 1],\n first = inertia[0],\n lastScale = map.transform.scaleZoom(startScale * last[1]),\n firstScale = map.transform.scaleZoom(startScale * first[1]),\n scaleOffset = lastScale - firstScale,\n scaleDuration = (last[0] - first[0]) / 1000,\n p = last[2];\n\n if (scaleDuration === 0 || lastScale === firstScale) {\n map.snapToNorth({}, { originalEvent: e });\n return;\n }\n\n // calculate scale/s speed and adjust for increased initial animation speed when easing\n let speed = scaleOffset * inertiaLinearity / scaleDuration; // scale/s\n\n if (Math.abs(speed) > inertiaMaxSpeed) {\n if (speed > 0) {\n speed = inertiaMaxSpeed;\n } else {\n speed = -inertiaMaxSpeed;\n }\n }\n\n const duration = Math.abs(speed / (inertiaDeceleration * inertiaLinearity)) * 1000;\n let targetScale = lastScale + speed * duration / 2000;\n\n if (targetScale < 0) {\n targetScale = 0;\n }\n\n map.easeTo({\n zoom: targetScale,\n duration,\n easing: inertiaEasing,\n around: this._aroundCenter ? map.getCenter() : map.unproject(p),\n noMoveStart: true\n }, { originalEvent: e });\n }\n\n _drainInertiaBuffer() {\n const inertia = this._inertia,\n now = browser.now(),\n cutoff = 160; // msec\n\n while (inertia.length > 2 && now - inertia[0][0] > cutoff) inertia.shift();\n }\n}\n\nexport default TouchZoomRotateHandler;\n","// @flow\n\nimport { MapMouseEvent, MapTouchEvent, MapWheelEvent } from '../ui/events';\nimport DOM from '../util/dom';\nimport type Map from './map';\nimport scrollZoom from './handler/scroll_zoom';\nimport boxZoom from './handler/box_zoom';\nimport dragRotate from './handler/drag_rotate';\nimport dragPan from './handler/drag_pan';\nimport keyboard from './handler/keyboard';\nimport doubleClickZoom from './handler/dblclick_zoom';\nimport touchZoomRotate from './handler/touch_zoom_rotate';\n\nconst handlers = {\n scrollZoom,\n boxZoom,\n dragRotate,\n dragPan,\n keyboard,\n doubleClickZoom,\n touchZoomRotate\n};\n\nexport default function bindHandlers(map: Map, options: {interactive: boolean, clickTolerance: number}) {\n const el = map.getCanvasContainer();\n let contextMenuEvent = null;\n let mouseDown = false;\n let startPos = null;\n\n for (const name in handlers) {\n (map: any)[name] = new handlers[name](map, options);\n if (options.interactive && options[name]) {\n (map: any)[name].enable(options[name]);\n }\n }\n\n DOM.addEventListener(el, 'mouseout', onMouseOut);\n DOM.addEventListener(el, 'mousedown', onMouseDown);\n DOM.addEventListener(el, 'mouseup', onMouseUp);\n DOM.addEventListener(el, 'mousemove', onMouseMove);\n DOM.addEventListener(el, 'mouseover', onMouseOver);\n\n // Bind touchstart and touchmove with passive: false because, even though\n // they only fire a map events and therefore could theoretically be\n // passive, binding with passive: true causes iOS not to respect\n // e.preventDefault() in _other_ handlers, even if they are non-passive\n // (see https://bugs.webkit.org/show_bug.cgi?id=184251)\n DOM.addEventListener(el, 'touchstart', onTouchStart, {passive: false});\n DOM.addEventListener(el, 'touchmove', onTouchMove, {passive: false});\n\n DOM.addEventListener(el, 'touchend', onTouchEnd);\n DOM.addEventListener(el, 'touchcancel', onTouchCancel);\n DOM.addEventListener(el, 'click', onClick);\n DOM.addEventListener(el, 'dblclick', onDblClick);\n DOM.addEventListener(el, 'contextmenu', onContextMenu);\n DOM.addEventListener(el, 'wheel', onWheel, {passive: false});\n\n function onMouseDown(e: MouseEvent) {\n mouseDown = true;\n startPos = DOM.mousePos(el, e);\n\n const mapEvent = new MapMouseEvent('mousedown', map, e);\n map.fire(mapEvent);\n\n if (mapEvent.defaultPrevented) {\n return;\n }\n\n if (options.interactive && !map.doubleClickZoom.isActive()) {\n map.stop();\n }\n\n map.boxZoom.onMouseDown(e);\n\n if (!map.boxZoom.isActive() && !map.dragPan.isActive()) {\n map.dragRotate.onMouseDown(e);\n }\n\n if (!map.boxZoom.isActive() && !map.dragRotate.isActive()) {\n map.dragPan.onMouseDown(e);\n }\n }\n\n function onMouseUp(e: MouseEvent) {\n const rotating = map.dragRotate.isActive();\n\n if (contextMenuEvent && !rotating) {\n // This will be the case for Mac\n map.fire(new MapMouseEvent('contextmenu', map, contextMenuEvent));\n }\n\n contextMenuEvent = null;\n mouseDown = false;\n\n map.fire(new MapMouseEvent('mouseup', map, e));\n }\n\n function onMouseMove(e: MouseEvent) {\n if (map.dragPan.isActive()) return;\n if (map.dragRotate.isActive()) return;\n\n let target: ?Node = (e.target: any);\n while (target && target !== el) target = target.parentNode;\n if (target !== el) return;\n\n map.fire(new MapMouseEvent('mousemove', map, e));\n }\n\n function onMouseOver(e: MouseEvent) {\n let target: ?Node = (e.target: any);\n while (target && target !== el) target = target.parentNode;\n if (target !== el) return;\n\n map.fire(new MapMouseEvent('mouseover', map, e));\n }\n\n function onMouseOut(e: MouseEvent) {\n map.fire(new MapMouseEvent('mouseout', map, e));\n }\n\n function onTouchStart(e: TouchEvent) {\n const mapEvent = new MapTouchEvent('touchstart', map, e);\n map.fire(mapEvent);\n\n if (mapEvent.defaultPrevented) {\n return;\n }\n\n if (options.interactive) {\n map.stop();\n }\n\n if (!map.boxZoom.isActive() && !map.dragRotate.isActive()) {\n map.dragPan.onTouchStart(e);\n }\n\n map.touchZoomRotate.onStart(e);\n map.doubleClickZoom.onTouchStart(mapEvent);\n }\n\n function onTouchMove(e: TouchEvent) {\n map.fire(new MapTouchEvent('touchmove', map, e));\n }\n\n function onTouchEnd(e: TouchEvent) {\n map.fire(new MapTouchEvent('touchend', map, e));\n }\n\n function onTouchCancel(e: TouchEvent) {\n map.fire(new MapTouchEvent('touchcancel', map, e));\n }\n\n function onClick(e: MouseEvent) {\n const pos = DOM.mousePos(el, e);\n if (!startPos || pos.equals(startPos) || pos.dist(startPos) < options.clickTolerance) {\n map.fire(new MapMouseEvent('click', map, e));\n }\n }\n\n function onDblClick(e: MouseEvent) {\n const mapEvent = new MapMouseEvent('dblclick', map, e);\n map.fire(mapEvent);\n\n if (mapEvent.defaultPrevented) {\n return;\n }\n\n map.doubleClickZoom.onDblClick(mapEvent);\n }\n\n function onContextMenu(e: MouseEvent) {\n const rotating = map.dragRotate.isActive();\n if (!mouseDown && !rotating) {\n // Windows: contextmenu fired on mouseup, so fire event now\n map.fire(new MapMouseEvent('contextmenu', map, e));\n } else if (mouseDown) {\n // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake\n contextMenuEvent = e;\n }\n\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 if (map.dragRotate.isEnabled() || map.listens('contextmenu')) {\n e.preventDefault();\n }\n }\n\n function onWheel(e: WheelEvent) {\n if (options.interactive) {\n map.stop();\n }\n\n const mapEvent = new MapWheelEvent('wheel', map, e);\n map.fire(mapEvent);\n\n if (mapEvent.defaultPrevented) {\n return;\n }\n\n map.scrollZoom.onWheel(e);\n }\n}\n","// @flow\n\nimport {\n bindAll,\n extend,\n deepEqual,\n warnOnce,\n clamp,\n wrap,\n ease as defaultEasing,\n pick\n} from '../util/util';\nimport { number as interpolate } from '../style-spec/util/interpolate';\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';\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 {PointLike} from '@mapbox/point-geometry';\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 * @typedef {Object} CameraOptions\n * @property {LngLatLike} center The desired center.\n * @property {number} zoom The desired zoom level.\n * @property {number} bearing The desired bearing, in degrees. The bearing is the compass direction that\n * is \"up\"; for example, a bearing of 90° orients the map so that east is up.\n * @property {number} pitch The desired pitch, in degrees.\n * @property {LngLatLike} around If `zoom` is specified, `around` determines the point around which the zoom is centered.\n */\nexport type CameraOptions = {\n center?: LngLatLike,\n zoom?: number,\n bearing?: number,\n pitch?: number,\n around?: LngLatLike\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 * @typedef {Object} AnimationOptions\n * @property {number} duration The animation's duration, measured in milliseconds.\n * @property {Function} easing 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 * @property {PointLike} offset of the target center relative to real map container center at the end of animation.\n * @property {boolean} animate If `false`, no animation will occur.\n */\nexport type AnimationOptions = {\n duration?: number,\n easing?: (number) => number,\n offset?: PointLike,\n animate?: boolean\n};\n\n/**\n * Options for setting padding on a call to {@link Map#fitBounds}. All properties of this object must be\n * non-negative integers.\n *\n * @typedef {Object} PaddingOptions\n * @property {number} top Padding in pixels from the top of the map canvas.\n * @property {number} bottom Padding in pixels from the bottom of the map canvas.\n * @property {number} left Padding in pixels from the left of the map canvas.\n * @property {number} right Padding in pixels from the right of the map canvas.\n */\n\nclass Camera extends Evented {\n transform: Transform;\n _moving: boolean;\n _zooming: boolean;\n _rotating: boolean;\n _pitching: boolean;\n\n _bearingSnap: number;\n _easeEndTimeoutID: TimeoutID;\n _easeStart: number;\n _easeOptions: {duration: number, easing: (number) => number};\n\n _onEaseFrame: (number) => void;\n _onEaseEnd: () => void;\n _easeFrameId: ?TaskID;\n\n +_requestRenderFrame: (() => void) => TaskID;\n +_cancelRenderFrame: (TaskID) => void;\n\n constructor(transform: Transform, options: {bearingSnap: number}) {\n super();\n this._moving = false;\n this._zooming = false;\n this.transform = transform;\n this._bearingSnap = options.bearingSnap;\n\n bindAll(['_renderFrameCallback'], this);\n }\n\n /**\n * Returns the map's geographical centerpoint.\n *\n * @memberof Map#\n * @returns The map's geographical centerpoint.\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 * @memberof Map#\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 * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n * @example\n * map.setCenter([-74, 38]);\n */\n setCenter(center: LngLatLike, eventData?: Object) {\n return this.jumpTo({center}, eventData);\n }\n\n /**\n * Pans the map by the specified offset.\n *\n * @memberof Map#\n * @param offset `x` and `y` coordinates by which to pan the map.\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)\n */\n panBy(offset: PointLike, options?: AnimationOptions, eventData?: Object) {\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 * @memberof Map#\n * @param lnglat The location to pan the map to.\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: Object) {\n return this.easeTo(extend({\n center: lnglat\n }, options), eventData);\n }\n\n /**\n * Returns the map's current zoom level.\n *\n * @memberof Map#\n * @returns The map's current zoom level.\n */\n getZoom(): number { return this.transform.zoom; }\n\n /**\n * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`.\n *\n * @memberof Map#\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 * @fires movestart\n * @fires zoomstart\n * @fires move\n * @fires zoom\n * @fires moveend\n * @fires zoomend\n * @returns {Map} `this`\n * @example\n * // zoom the map to 5\n * map.setZoom(5);\n */\n setZoom(zoom: number, eventData?: Object) {\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 * @memberof Map#\n * @param zoom The zoom level to transition to.\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires move\n * @fires zoom\n * @fires moveend\n * @fires zoomend\n * @returns {Map} `this`\n */\n zoomTo(zoom: number, options: ? AnimationOptions, eventData?: Object) {\n return this.easeTo(extend({\n zoom\n }, options), eventData);\n }\n\n /**\n * Increases the map's zoom level by 1.\n *\n * @memberof Map#\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires move\n * @fires zoom\n * @fires moveend\n * @fires zoomend\n * @returns {Map} `this`\n */\n zoomIn(options?: AnimationOptions, eventData?: Object) {\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 * @memberof Map#\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires move\n * @fires zoom\n * @fires moveend\n * @fires zoomend\n * @returns {Map} `this`\n */\n zoomOut(options?: AnimationOptions, eventData?: Object) {\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 * @memberof Map#\n * @returns The map's current bearing.\n * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/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 * @memberof Map#\n * @param bearing The desired bearing.\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n * @example\n * // rotate the map to 90 degrees\n * map.setBearing(90);\n */\n setBearing(bearing: number, eventData?: Object) {\n this.jumpTo({bearing}, 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 * @memberof Map#\n * @param bearing The desired bearing.\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n rotateTo(bearing: number, options?: AnimationOptions, eventData?: Object) {\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 * @memberof Map#\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n resetNorth(options?: AnimationOptions, eventData?: Object) {\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 * @memberof Map#\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n resetNorthPitch(options?: AnimationOptions, eventData?: Object) {\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 * @memberof Map#\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n snapToNorth(options?: AnimationOptions, eventData?: Object) {\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 * @memberof Map#\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 * @memberof Map#\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 * @fires pitchstart\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n setPitch(pitch: number, eventData?: Object) {\n this.jumpTo({pitch}, eventData);\n return this;\n }\n\n /**\n * @memberof Map#\n * @param {LatLngBoundsLike} 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. LatLngBounds represent a box that is always axis-aligned with bearing 0.\n * @param options\n * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.\n * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.\n * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds.\n * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with\n * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined.\n * @example\n * var bbox = [[-79, 43], [-73, 45]];\n * var newCameraTransform = map.cameraForBounds(bbox, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n */\n cameraForBounds(bounds: LngLatBoundsLike, options?: CameraOptions): void | CameraOptions & AnimationOptions {\n bounds = LngLatBounds.convert(bounds);\n return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), 0, options);\n }\n\n /**\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 * @memberof Map#\n * @param {LngLatLike} p0 First point\n * @param {LngLatLike} p1 Second point\n * @param bearing Desired map bearing at end of animation, in degrees\n * @param options\n * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.\n * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.\n * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds.\n * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with\n * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined.\n * @private\n * @example\n * var p0 = [-79, 43];\n * var p1 = [-73, 45];\n * var bearing = 90;\n * var newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n */\n _cameraForBoxAndBearing(p0: LngLatLike, p1: LngLatLike, bearing: number, options?: CameraOptions): void | CameraOptions & AnimationOptions {\n options = extend({\n padding: {\n top: 0,\n bottom: 0,\n right: 0,\n left: 0\n },\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 if (!deepEqual(Object.keys(options.padding).sort((a, b) => {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n }), [\"bottom\", \"left\", \"right\", \"top\"])) {\n warnOnce(\n \"options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'\"\n );\n return;\n }\n\n const tr = this.transform;\n\n // We want to calculate the upper right and lower left of the box defined by p0 and p1\n // in a coordinate system rotate to match the destination bearing.\n const p0world = tr.project(LngLat.convert(p0));\n const p1world = tr.project(LngLat.convert(p1));\n const p0rotated = p0world.rotate(-bearing * Math.PI / 180);\n const p1rotated = p1world.rotate(-bearing * Math.PI / 180);\n\n const upperRight = new Point(Math.max(p0rotated.x, p1rotated.x), Math.max(p0rotated.y, p1rotated.y));\n const lowerLeft = new Point(Math.min(p0rotated.x, p1rotated.x), Math.min(p0rotated.y, p1rotated.y));\n\n // Calculate zoom: consider the original bbox and padding.\n const size = upperRight.sub(lowerLeft);\n const scaleX = (tr.width - options.padding.left - options.padding.right) / size.x;\n const scaleY = (tr.height - 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;\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 offsetAtInitialZoom = new Point(offset.x + paddingOffsetX, offset.y + paddingOffsetY);\n const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom));\n\n const center = tr.unproject(p0world.add(p1world).div(2).sub(offsetAtFinalZoom));\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 * @memberof Map#\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 * @param {Object} [options] Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below.\n * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.\n * @param {boolean} [options.linear=false] If `true`, the map transitions using\n * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See\n * those functions and {@link AnimationOptions} for information about options available.\n * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}.\n * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.\n * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds.\n * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n\t * @example\n * var bbox = [[-79, 43], [-73, 45]];\n * map.fitBounds(bbox, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * @see [Fit a map to a bounding box](https://www.mapbox.com/mapbox-gl-js/example/fitbounds/)\n */\n fitBounds(bounds: LngLatBoundsLike, options?: AnimationOptions & CameraOptions, eventData?: Object) {\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 * @memberof Map#\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\n * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.\n * @param {boolean} [options.linear=false] If `true`, the map transitions using\n * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See\n * those functions and {@link AnimationOptions} for information about options available.\n * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}.\n * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.\n * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds.\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n\t * @example\n * var p0 = [220, 400];\n * var p1 = [500, 900];\n * map.fitScreenCoordinates(p0, p1, map.getBearing(), {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * @see [Used by BoxZoomHandler](https://www.mapbox.com/mapbox-gl-js/api/#boxzoomhandler)\n */\n fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: AnimationOptions & CameraOptions, eventData?: Object) {\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?: CameraOptions & AnimationOptions, options?: AnimationOptions & CameraOptions, eventData?: Object) {\n // cameraForBounds warns + returns undefined if unable to fit:\n if (!calculatedOptions) return this;\n\n options = extend(calculatedOptions, options);\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 * @memberof Map#\n * @param options\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires pitchstart\n * @fires rotate\n * @fires move\n * @fires zoom\n * @fires pitch\n * @fires moveend\n * @fires zoomend\n * @fires pitchend\n * @returns {Map} `this`\n */\n jumpTo(options: CameraOptions, eventData?: Object) {\n this.stop();\n\n const tr = this.transform;\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 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 * Changes any combination of center, zoom, bearing, and pitch, 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` accesibility feature enabled in their operating system.\n *\n * @memberof Map#\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 * @fires movestart\n * @fires zoomstart\n * @fires pitchstart\n * @fires rotate\n * @fires move\n * @fires zoom\n * @fires pitch\n * @fires moveend\n * @fires zoomend\n * @fires pitchend\n * @returns {Map} `this`\n * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)\n */\n easeTo(options: CameraOptions & AnimationOptions & {delayEndEvents?: number}, eventData?: Object) {\n this.stop();\n\n options = extend({\n offset: [0, 0],\n duration: 500,\n easing: defaultEasing\n }, options);\n\n if (options.animate === false || browser.prefersReducedMotion) options.duration = 0;\n\n const tr = this.transform,\n startZoom = this.getZoom(),\n startBearing = this.getBearing(),\n startPitch = this.getPitch(),\n\n zoom = 'zoom' in options ? +options.zoom : startZoom,\n bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing,\n pitch = 'pitch' in options ? +options.pitch : startPitch;\n\n const pointAtOffset = tr.centerPoint.add(Point.convert(options.offset));\n const locationAtOffset = tr.pointLocation(pointAtOffset);\n const center = LngLat.convert(options.center || locationAtOffset);\n this._normalizeCenter(center);\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 this._zooming = (zoom !== startZoom);\n this._rotating = (startBearing !== bearing);\n this._pitching = (pitch !== startPitch);\n\n this._prepareEase(eventData, options.noMoveStart);\n\n clearTimeout(this._easeEndTimeoutID);\n\n this._ease((k) => {\n if (this._zooming) {\n tr.zoom = interpolate(startZoom, zoom, k);\n }\n if (this._rotating) {\n tr.bearing = interpolate(startBearing, bearing, k);\n }\n if (this._pitching) {\n tr.pitch = interpolate(startPitch, pitch, k);\n }\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._fireMoveEvents(eventData);\n\n }, () => {\n if (options.delayEndEvents) {\n this._easeEndTimeoutID = setTimeout(() => this._afterEase(eventData), options.delayEndEvents);\n } else {\n this._afterEase(eventData);\n }\n }, options);\n\n return this;\n }\n\n _prepareEase(eventData?: Object, noMoveStart: boolean) {\n this._moving = true;\n\n if (!noMoveStart) {\n this.fire(new Event('movestart', eventData));\n }\n if (this._zooming) {\n this.fire(new Event('zoomstart', eventData));\n }\n if (this._rotating) {\n this.fire(new Event('rotatestart', eventData));\n }\n if (this._pitching) {\n this.fire(new Event('pitchstart', eventData));\n }\n }\n\n _fireMoveEvents(eventData?: Object) {\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?: Object) {\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\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` accesibility feature enabled in their operating system.\n *\n * @memberof Map#\n * @param {Object} options Options describing the destination and animation of the transition.\n * Accepts {@link CameraOptions}, {@link AnimationOptions},\n * and the following additional options.\n * @param {number} [options.curve=1.42] 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 * @param {number} [options.minZoom] The zero-based zoom level at the peak of the flight path. If\n * `options.curve` is specified, this option is ignored.\n * @param {number} [options.speed=1.2] 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 * @param {number} [options.screenSpeed] 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 * @param {number} [options.maxDuration] The animation's maximum duration, measured in milliseconds.\n * If duration exceeds maximum duration, it resets to 0.\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires pitchstart\n * @fires move\n * @fires zoom\n * @fires rotate\n * @fires pitch\n * @fires moveend\n * @fires zoomend\n * @fires pitchend\n * @returns {Map} `this`\n * @example\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 * @see [Fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto/)\n * @see [Slowly fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto-options/)\n * @see [Fly to a location based on scroll position](https://www.mapbox.com/mapbox-gl-js/example/scroll-fly-to/)\n */\n flyTo(options: Object, eventData?: Object) {\n // Fall through to jumpTo if user has set prefers-reduced-motion\n if (browser.prefersReducedMotion) {\n const coercedOptions = (pick(options, ['center', 'zoom', 'bearing', 'pitch', 'around']): 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.transform,\n startZoom = this.getZoom(),\n startBearing = this.getBearing(),\n startPitch = this.getPitch();\n\n const zoom = 'zoom' in options ? clamp(+options.zoom, tr.minZoom, tr.maxZoom) : startZoom;\n const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing;\n const pitch = 'pitch' in options ? +options.pitch : startPitch;\n\n const scale = tr.zoomScale(zoom - startZoom);\n const pointAtOffset = tr.centerPoint.add(Point.convert(options.offset));\n const locationAtOffset = tr.pointLocation(pointAtOffset);\n const center = LngLat.convert(options.center || locationAtOffset);\n this._normalizeCenter(center);\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 i 0 for the ascent or 1 for the descent.\n * @private\n */\n function r(i) {\n const b = (w1 * w1 - w0 * w0 + (i ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (i ? 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 = r(0);\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 = (r(1) - 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 = function() { return 0; };\n w = function(s) { return 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\n this._prepareEase(eventData, false);\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 = interpolate(startBearing, bearing, k);\n }\n if (this._pitching) {\n tr.pitch = interpolate(startPitch, pitch, k);\n }\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._fireMoveEvents(eventData);\n\n }, () => this._afterEase(eventData), options);\n\n return this;\n }\n\n isEasing() {\n return !!this._easeFrameId;\n }\n\n /**\n * Stops any animated transition underway.\n *\n * @memberof Map#\n * @returns {Map} `this`\n */\n stop(): 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);\n }\n return this;\n }\n\n _ease(frame: (number) => void,\n finish: () => void,\n options: {animate: boolean, duration: number, easing: (number) => number}) {\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 if (t < 1) {\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) {\n const tr = this.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\nexport default Camera;\n","// @flow\n\nimport DOM from '../../util/dom';\nimport { bindAll } from '../../util/util';\nimport config from '../../util/config';\n\nimport type Map from '../map';\n\ntype Options = {\n compact?: boolean,\n customAttribution?: string | Array\n};\n\n/**\n * An `AttributionControl` control presents the map's [attribution information](https://www.mapbox.com/help/attribution/).\n *\n * @implements {IControl}\n * @param {Object} [options]\n * @param {boolean} [options.compact] If `true` force a compact attribution that shows the full attribution on mouse hover, or if `false` force the full attribution control. The default is a responsive attribution that collapses when the map is less than 640 pixels wide.\n * @param {string | Array} [options.customAttribution] String or strings to show in addition to any other attributions.\n * @example\n * var map = new mapboxgl.Map({attributionControl: false})\n * .addControl(new mapboxgl.AttributionControl({\n * compact: true\n * }));\n */\nclass AttributionControl {\n options: Options;\n _map: Map;\n _container: HTMLElement;\n _innerContainer: HTMLElement;\n _editLink: ?HTMLAnchorElement;\n _attribHTML: string;\n styleId: string;\n styleOwner: string;\n\n constructor(options: Options = {}) {\n this.options = options;\n\n bindAll([\n '_updateEditLink',\n '_updateData',\n '_updateCompact'\n ], this);\n }\n\n getDefaultPosition() {\n return 'bottom-right';\n }\n\n onAdd(map: Map) {\n const compact = this.options && this.options.compact;\n\n this._map = map;\n this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-attrib');\n this._innerContainer = DOM.create('div', 'mapboxgl-ctrl-attrib-inner', this._container);\n\n if (compact) {\n this._container.classList.add('mapboxgl-compact');\n }\n\n this._updateAttributions();\n this._updateEditLink();\n\n this._map.on('styledata', this._updateData);\n this._map.on('sourcedata', this._updateData);\n this._map.on('moveend', this._updateEditLink);\n\n if (compact === undefined) {\n this._map.on('resize', this._updateCompact);\n this._updateCompact();\n }\n\n return this._container;\n }\n\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('moveend', this._updateEditLink);\n this._map.off('resize', this._updateCompact);\n\n this._map = (undefined: any);\n }\n\n _updateEditLink() {\n let editLink = this._editLink;\n if (!editLink) {\n editLink = this._editLink = (this._container.querySelector('.mapbox-improve-map'): any);\n }\n\n const params = [\n {key: \"owner\", value: this.styleOwner},\n {key: \"id\", value: this.styleId},\n {key: \"access_token\", value: this._map._requestManager._customAccessToken || config.ACCESS_TOKEN}\n ];\n\n if (editLink) {\n const paramString = params.reduce((acc, next, i) => {\n if (next.value) {\n acc += `${next.key}=${next.value}${i < params.length - 1 ? '&' : ''}`;\n }\n return acc;\n }, `?`);\n editLink.href = `${config.FEEDBACK_URL}/${paramString}${this._map._hash ? this._map._hash.getHashString(true) : ''}`;\n editLink.rel = \"noopener nofollow\";\n }\n }\n\n _updateData(e: any) {\n if (e && (e.sourceDataType === 'metadata' || e.dataType === 'style')) {\n this._updateAttributions();\n this._updateEditLink();\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: any = this._map.style.stylesheet;\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) {\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 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('mapboxgl-attrib-empty');\n } else {\n this._container.classList.add('mapboxgl-attrib-empty');\n }\n // remove old DOM node from _editLink\n this._editLink = null;\n }\n\n _updateCompact() {\n if (this._map.getCanvasContainer().offsetWidth <= 640) {\n this._container.classList.add('mapboxgl-compact');\n } else {\n this._container.classList.remove('mapboxgl-compact');\n }\n }\n\n}\n\nexport default AttributionControl;\n","// @flow\n\nimport DOM from '../../util/dom';\n\nimport { bindAll } from '../../util/util';\n\nimport type Map from '../map';\n\n/**\n * A `LogoControl` is a control that adds the Mapbox watermark\n * to the map as required by the [terms of service](https://www.mapbox.com/tos/) for Mapbox\n * vector tiles and core styles.\n *\n * @implements {IControl}\n * @private\n**/\n\nclass LogoControl {\n _map: Map;\n _container: HTMLElement;\n\n constructor() {\n bindAll(['_updateLogo'], this);\n bindAll(['_updateCompact'], this);\n }\n\n onAdd(map: Map) {\n this._map = map;\n this._container = DOM.create('div', 'mapboxgl-ctrl');\n const anchor = DOM.create('a', 'mapboxgl-ctrl-logo');\n anchor.target = \"_blank\";\n anchor.rel = \"noopener nofollow\";\n anchor.href = \"https://www.mapbox.com/\";\n anchor.setAttribute(\"aria-label\", \"Mapbox logo\");\n anchor.setAttribute(\"rel\", \"noopener nofollow\");\n this._container.appendChild(anchor);\n this._container.style.display = 'none';\n\n this._map.on('sourcedata', this._updateLogo);\n this._updateLogo();\n\n this._map.on('resize', this._updateCompact);\n this._updateCompact();\n\n return this._container;\n }\n\n onRemove() {\n DOM.remove(this._container);\n this._map.off('sourcedata', this._updateLogo);\n this._map.off('resize', this._updateCompact);\n }\n\n getDefaultPosition() {\n return 'bottom-left';\n }\n\n _updateLogo(e: any) {\n if (!e || e.sourceDataType === 'metadata') {\n this._container.style.display = this._logoRequired() ? 'block' : 'none';\n }\n }\n\n _logoRequired() {\n if (!this._map.style) return;\n\n const sourceCaches = this._map.style.sourceCaches;\n for (const id in sourceCaches) {\n const source = sourceCaches[id].getSource();\n if (source.mapbox_logo) {\n return true;\n }\n }\n\n return false;\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 < 250) {\n anchor.classList.add('mapboxgl-compact');\n } else {\n anchor.classList.remove('mapboxgl-compact');\n }\n }\n }\n\n}\n\nexport default LogoControl;\n","// @flow strict\nimport assert from 'assert';\n\nexport type TaskID = number; // can't mark opaque due to https://github.com/flowtype/flow-remove-types/pull/61\ntype Task = {\n callback: () => void;\n id: TaskID;\n cancelled: boolean;\n};\n\nclass 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: () => 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() {\n assert(!this._currentlyRunning);\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();\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\nexport default TaskQueue;\n","// @flow\n\nimport { version } from '../../package.json';\nimport { extend, bindAll, warnOnce, uniqueId } from '../util/util';\nimport browser from '../util/browser';\nimport window from '../util/window';\nconst { HTMLImageElement, HTMLElement } = window;\nimport DOM from '../util/dom';\nimport { getImage, getJSON, ResourceType } from '../util/ajax';\nimport { RequestManager } from '../util/mapbox';\nimport Style from '../style/style';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport Painter from '../render/painter';\nimport Transform from '../geo/transform';\nimport Hash from './hash';\nimport bindHandlers from './bind_handlers';\nimport Camera from './camera';\nimport LngLat from '../geo/lng_lat';\nimport LngLatBounds from '../geo/lng_lat_bounds';\nimport Point from '@mapbox/point-geometry';\nimport AttributionControl from './control/attribution_control';\nimport LogoControl from './control/logo_control';\nimport isSupported from '@mapbox/mapbox-gl-supported';\nimport { RGBAImage } from '../util/image';\nimport { Event, ErrorEvent } from '../util/evented';\nimport { MapMouseEvent } from './events';\nimport TaskQueue from '../util/task_queue';\nimport webpSupported from '../util/webp_supported';\nimport { setCacheLimits } from '../util/tile_request_cache';\n\nimport type {PointLike} from '@mapbox/point-geometry';\nimport type { RequestTransformFunction } from '../util/mapbox';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport type {LngLatBoundsLike} from '../geo/lng_lat_bounds';\nimport type {StyleOptions, StyleSetterOptions} from '../style/style';\nimport type {MapEvent, MapDataEvent} from './events';\nimport type {CustomLayerInterface} from '../style/style_layer/custom_style_layer';\nimport type {StyleImageInterface} from '../style/style_image';\n\nimport type ScrollZoomHandler from './handler/scroll_zoom';\nimport type BoxZoomHandler from './handler/box_zoom';\nimport type DragRotateHandler from './handler/drag_rotate';\nimport type DragPanHandler from './handler/drag_pan';\nimport type KeyboardHandler from './handler/keyboard';\nimport type DoubleClickZoomHandler from './handler/dblclick_zoom';\nimport type TouchZoomRotateHandler from './handler/touch_zoom_rotate';\nimport type {TaskID} from '../util/task_queue';\nimport type {Cancelable} from '../types/cancelable';\nimport type {\n LayerSpecification,\n FilterSpecification,\n StyleSpecification,\n LightSpecification,\n SourceSpecification\n} from '../style-spec/types';\n\ntype ControlPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n/* eslint-disable no-use-before-define */\ntype IControl = {\n onAdd(map: Map): HTMLElement;\n onRemove(map: Map): void;\n\n +getDefaultPosition?: () => ControlPosition;\n}\n/* eslint-enable no-use-before-define */\n\ntype MapOptions = {\n hash?: boolean,\n interactive?: boolean,\n container: HTMLElement | string,\n bearingSnap?: number,\n attributionControl?: boolean,\n customAttribution?: string | Array,\n logoPosition?: ControlPosition,\n failIfMajorPerformanceCaveat?: boolean,\n preserveDrawingBuffer?: boolean,\n antialias?: boolean,\n refreshExpiredTiles?: boolean,\n maxBounds?: LngLatBoundsLike,\n scrollZoom?: boolean,\n minZoom?: ?number,\n maxZoom?: ?number,\n boxZoom?: boolean,\n dragRotate?: boolean,\n dragPan?: boolean,\n keyboard?: boolean,\n doubleClickZoom?: boolean,\n touchZoomRotate?: boolean,\n trackResize?: boolean,\n center?: LngLatLike,\n zoom?: number,\n bearing?: number,\n pitch?: number,\n renderWorldCopies?: boolean,\n maxTileCacheSize?: number,\n transformRequest?: RequestTransformFunction,\n accessToken: string\n};\n\nconst defaultMinZoom = 0;\nconst defaultMaxZoom = 22;\nconst defaultOptions = {\n center: [0, 0],\n zoom: 0,\n bearing: 0,\n pitch: 0,\n\n minZoom: defaultMinZoom,\n maxZoom: defaultMaxZoom,\n\n interactive: true,\n scrollZoom: true,\n boxZoom: true,\n dragRotate: true,\n dragPan: true,\n keyboard: true,\n doubleClickZoom: true,\n touchZoomRotate: true,\n\n bearingSnap: 7,\n clickTolerance: 3,\n\n hash: false,\n attributionControl: true,\n\n failIfMajorPerformanceCaveat: false,\n preserveDrawingBuffer: false,\n trackResize: true,\n renderWorldCopies: true,\n refreshExpiredTiles: true,\n maxTileCacheSize: null,\n localIdeographFontFamily: 'sans-serif',\n transformRequest: null,\n accessToken: null,\n fadeDuration: 300,\n crossSourceCollisions: 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.\n * Then Mapbox GL JS initializes the map on the page and returns your `Map`\n * object.\n *\n * @extends Evented\n * @param {Object} options\n * @param {HTMLElement|string} options.container The HTML element in which Mapbox GL JS will render the map, or the element's string `id`. The specified element must have no children.\n * @param {number} [options.minZoom=0] The minimum zoom level of the map (0-24).\n * @param {number} [options.maxZoom=22] The maximum zoom level of the map (0-24).\n * @param {Object|string} [options.style] The map's Mapbox style. This must be an a JSON object conforming to\n * the schema described in the [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to\n * such JSON.\n *\n * To load a style from the Mapbox API, you can use a URL of the form `mapbox://styles/:owner/:style`,\n * where `:owner` is your Mapbox account name and `:style` is the style ID. Or you can use one of the following\n * [the predefined Mapbox styles](https://www.mapbox.com/maps/):\n *\n * * `mapbox://styles/mapbox/streets-v10`\n * * `mapbox://styles/mapbox/outdoors-v10`\n * * `mapbox://styles/mapbox/light-v9`\n * * `mapbox://styles/mapbox/dark-v9`\n * * `mapbox://styles/mapbox/satellite-v9`\n * * `mapbox://styles/mapbox/satellite-streets-v10`\n * * `mapbox://styles/mapbox/navigation-preview-day-v2`\n * * `mapbox://styles/mapbox/navigation-preview-night-v2`\n * * `mapbox://styles/mapbox/navigation-guidance-day-v2`\n * * `mapbox://styles/mapbox/navigation-guidance-night-v2`\n *\n * Tilesets hosted with Mapbox can be style-optimized if you append `?optimize=true` to the end of your style URL, like `mapbox://styles/mapbox/streets-v9?optimize=true`.\n * Learn more about style-optimized vector tiles in our [API documentation](https://www.mapbox.com/api-documentation/maps/#retrieve-tiles).\n *\n * @param {boolean} [options.hash=false] 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 * @param {boolean} [options.interactive=true] If `false`, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction.\n * @param {number} [options.bearingSnap=7] 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 * @param {boolean} [options.pitchWithRotate=true] If `false`, the map's pitch (tilt) control with \"drag to rotate\" interaction will be disabled.\n * @param {number} [options.clickTolerance=3] 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 * @param {boolean} [options.attributionControl=true] If `true`, an {@link AttributionControl} will be added to the map.\n * @param {string | Array} [options.customAttribution] String or strings to show in an {@link AttributionControl}. Only applicable if `options.attributionControl` is `true`.\n * @param {string} [options.logoPosition='bottom-left'] A string representing the position of the Mapbox wordmark on the map. Valid options are `top-left`,`top-right`, `bottom-left`, `bottom-right`.\n * @param {boolean} [options.failIfMajorPerformanceCaveat=false] If `true`, map creation will fail if the performance of Mapbox\n * GL JS would be dramatically worse than expected (i.e. a software renderer would be used).\n * @param {boolean} [options.preserveDrawingBuffer=false] 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 * @param {boolean} [options.antialias] If `true`, the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. this is `false` by default as a performance optimization.\n * @param {boolean} [options.refreshExpiredTiles=true] If `false`, the map won't attempt to re-request tiles once they expire per their HTTP `cacheControl`/`expires` headers.\n * @param {LngLatBoundsLike} [options.maxBounds] If set, the map will be constrained to the given bounds.\n * @param {boolean|Object} [options.scrollZoom=true] If `true`, the \"scroll to zoom\" interaction is enabled. An `Object` value is passed as options to {@link ScrollZoomHandler#enable}.\n * @param {boolean} [options.boxZoom=true] If `true`, the \"box zoom\" interaction is enabled (see {@link BoxZoomHandler}).\n * @param {boolean} [options.dragRotate=true] If `true`, the \"drag to rotate\" interaction is enabled (see {@link DragRotateHandler}).\n * @param {boolean} [options.dragPan=true] If `true`, the \"drag to pan\" interaction is enabled (see {@link DragPanHandler}).\n * @param {boolean} [options.keyboard=true] If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}).\n * @param {boolean} [options.doubleClickZoom=true] If `true`, the \"double click to zoom\" interaction is enabled (see {@link DoubleClickZoomHandler}).\n * @param {boolean|Object} [options.touchZoomRotate=true] If `true`, the \"pinch to rotate and zoom\" interaction is enabled. An `Object` value is passed as options to {@link TouchZoomRotateHandler#enable}.\n * @param {boolean} [options.trackResize=true] If `true`, the map will automatically resize when the browser window resizes.\n * @param {LngLatLike} [options.center=[0, 0]] The inital geographical centerpoint of the map. If `center` is not specified in the constructor options, Mapbox 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: Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.\n * @param {number} [options.zoom=0] The initial zoom level of the map. If `zoom` is not specified in the constructor options, Mapbox 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 * @param {number} [options.bearing=0] The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If `bearing` is not specified in the constructor options, Mapbox 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 * @param {number} [options.pitch=0] The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-60). If `pitch` is not specified in the constructor options, Mapbox 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 * @param {LngLatBoundsLike} [options.bounds] The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options.\n * @param {Object} [options.fitBoundsOptions] A [`fitBounds`](#map#fitbounds) options object to use _only_ when fitting the initial `bounds` provided above.\n * @param {boolean} [options.renderWorldCopies=true] If `true`, multiple copies of the world will be rendered, when zoomed out.\n * @param {number} [options.maxTileCacheSize=null] 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.\n * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS\n * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges.\n * In these ranges, 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. Note that [Mapbox Studio](https://studio.mapbox.com/) sets this value to `false` by default.\n * The purpose of this option is to avoid bandwidth-intensive glyph server requests. (See [Use locally generated ideographs](https://www.mapbox.com/mapbox-gl-js/example/local-ideographs).)\n * @param {RequestTransformFunction} [options.transformRequest=null] 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 * @param {boolean} [options.collectResourceTiming=false] 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 * @param {number} [options.fadeDuration=300] Controls the duration of the fade-in/fade-out animation for label collisions, 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 * @param {boolean} [options.crossSourceCollisions=true] 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 * @param {string} [options.accessToken=null] If specified, map will use this token instead of the one defined in mapboxgl.accessToken.\n\n * @example\n * var map = new mapboxgl.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 * @see [Display a map](https://www.mapbox.com/mapbox-gl-js/examples/)\n */\nclass Map extends Camera {\n style: Style;\n painter: Painter;\n\n _container: HTMLElement;\n _missingCSSCanary: HTMLElement;\n _canvasContainer: HTMLElement;\n _controlContainer: HTMLElement;\n _controlPositions: {[string]: HTMLElement};\n _interactive: ?boolean;\n _showTileBoundaries: ?boolean;\n _showCollisionBoxes: ?boolean;\n _showOverdrawInspector: boolean;\n _repaint: ?boolean;\n _vertices: ?boolean;\n _canvas: HTMLCanvasElement;\n _maxTileCacheSize: number;\n _frame: ?Cancelable;\n _styleDirty: ?boolean;\n _sourcesDirty: ?boolean;\n _placementDirty: ?boolean;\n _loaded: boolean;\n _trackResize: boolean;\n _preserveDrawingBuffer: boolean;\n _failIfMajorPerformanceCaveat: boolean;\n _antialias: boolean;\n _refreshExpiredTiles: boolean;\n _hash: Hash;\n _delegatedListeners: any;\n _fadeDuration: number;\n _crossSourceCollisions: boolean;\n _crossFadingFactor: number;\n _collectResourceTiming: boolean;\n _renderTaskQueue: TaskQueue;\n _controls: Array;\n _mapId: number;\n _localIdeographFontFamily: string;\n _requestManager: RequestManager;\n\n /**\n * The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad.\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 */\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.\n */\n dragRotate: DragRotateHandler;\n\n /**\n * The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture.\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.\n */\n keyboard: KeyboardHandler;\n\n /**\n * The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking.\n */\n doubleClickZoom: DoubleClickZoomHandler;\n\n /**\n * The map's {@link TouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures.\n */\n touchZoomRotate: TouchZoomRotateHandler;\n\n constructor(options: MapOptions) {\n options = extend({}, defaultOptions, options);\n\n if (options.minZoom != null && options.maxZoom != null && options.minZoom > options.maxZoom) {\n throw new Error(`maxZoom must be greater than minZoom`);\n }\n\n const transform = new Transform(options.minZoom, options.maxZoom, options.renderWorldCopies);\n super(transform, options);\n\n this._interactive = options.interactive;\n this._maxTileCacheSize = options.maxTileCacheSize;\n this._failIfMajorPerformanceCaveat = options.failIfMajorPerformanceCaveat;\n this._preserveDrawingBuffer = options.preserveDrawingBuffer;\n this._antialias = options.antialias;\n this._trackResize = options.trackResize;\n this._bearingSnap = options.bearingSnap;\n this._refreshExpiredTiles = options.refreshExpiredTiles;\n this._fadeDuration = options.fadeDuration;\n this._crossSourceCollisions = options.crossSourceCollisions;\n this._crossFadingFactor = 1;\n this._collectResourceTiming = options.collectResourceTiming;\n this._renderTaskQueue = new TaskQueue();\n this._controls = [];\n this._mapId = uniqueId();\n\n this._requestManager = new RequestManager(options.transformRequest, options.accessToken);\n\n if (typeof options.container === 'string') {\n this._container = window.document.getElementById(options.container);\n if (!this._container) {\n throw new Error(`Container '${options.container}' not found.`);\n }\n } else if (options.container instanceof HTMLElement) {\n this._container = options.container;\n } else {\n throw new Error(`Invalid type: 'container' must be a String or HTMLElement.`);\n }\n\n if (options.maxBounds) {\n this.setMaxBounds(options.maxBounds);\n }\n\n bindAll([\n '_onWindowOnline',\n '_onWindowResize',\n '_contextLost',\n '_contextRestored'\n ], this);\n\n this._setupContainer();\n this._setupPainter();\n if (this.painter === undefined) {\n throw new Error(`Failed to initialize WebGL.`);\n }\n\n this.on('move', () => this._update(false));\n this.on('moveend', () => this._update(false));\n this.on('zoom', () => this._update(true));\n\n if (typeof window !== 'undefined') {\n window.addEventListener('online', this._onWindowOnline, false);\n window.addEventListener('resize', this._onWindowResize, false);\n }\n\n bindHandlers(this, options);\n\n this._hash = options.hash && (new Hash()).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: options.center,\n zoom: options.zoom,\n bearing: options.bearing,\n pitch: options.pitch\n });\n\n if (options.bounds) {\n this.resize();\n this.fitBounds(options.bounds, extend({}, options.fitBoundsOptions, { duration: 0 }));\n }\n }\n\n this.resize();\n\n this._localIdeographFontFamily = options.localIdeographFontFamily;\n if (options.style) this.setStyle(options.style, { localIdeographFontFamily: options.localIdeographFontFamily });\n\n if (options.attributionControl)\n this.addControl(new AttributionControl({ customAttribution: options.customAttribution }));\n\n this.addControl(new LogoControl(), options.logoPosition);\n\n this.on('style.load', () => {\n if (this.transform.unmodified) {\n this.jumpTo((this.style.stylesheet: 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 }\n\n /*\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 * @private\n * @returns {number}\n */\n _getMapId() {\n return this._mapId;\n }\n\n /**\n * Adds a {@link IControl} to the map, calling `control.onAdd(this)`.\n *\n * @param {IControl} control The {@link IControl} to add.\n * @param {string} [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 * @returns {Map} `this`\n * @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/)\n */\n addControl(control: IControl, position?: ControlPosition) {\n if (position === undefined && control.getDefaultPosition) {\n position = control.getDefaultPosition();\n }\n if (position === undefined) {\n position = 'top-right';\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 * @param {IControl} control The {@link IControl} to remove.\n * @returns {Map} `this`\n */\n removeControl(control: IControl) {\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 * Resizes the map according to the dimensions of its\n * `container` element.\n *\n * This method must be called after the map's `container` is resized by another script,\n * or when the map is shown after being initially hidden with CSS.\n *\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @returns {Map} `this`\n */\n resize(eventData?: Object) {\n const dimensions = this._containerDimensions();\n const width = dimensions[0];\n const height = dimensions[1];\n\n this._resizeCanvas(width, height);\n this.transform.resize(width, height);\n this.painter.resize(width, height);\n\n this.fire(new Event('movestart', eventData))\n .fire(new Event('move', eventData))\n .fire(new Event('resize', eventData))\n .fire(new Event('moveend', eventData));\n return this;\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 */\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 */\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 {LngLatBoundsLike | null | undefined} bounds The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds.\n * @returns {Map} `this`\n */\n setMaxBounds(bounds: LngLatBoundsLike) {\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 * @param {number | null | undefined} minZoom The minimum zoom level to set (0-24).\n * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to 0).\n * @returns {Map} `this`\n */\n setMinZoom(minZoom?: ?number) {\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 {number} minZoom\n */\n getMinZoom() { 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 * @param {number | null | undefined} 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 * @returns {Map} `this`\n */\n setMaxZoom(maxZoom?: ?number) {\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 state of renderWorldCopies.\n *\n * @returns {boolean} renderWorldCopies\n */\n getRenderWorldCopies() { return this.transform.renderWorldCopies; }\n\n /**\n * Sets the state of renderWorldCopies.\n *\n * @param {boolean} renderWorldCopies If `true`, multiple copies of the world will be rendered, when zoomed out. `undefined` is treated as `true`, `null` is treated as `false`.\n * @returns {Map} `this`\n */\n setRenderWorldCopies(renderWorldCopies?: ?boolean) {\n this.transform.renderWorldCopies = renderWorldCopies;\n return this._update();\n }\n\n /**\n * Returns the map's maximum allowable zoom level.\n *\n * @returns {number} maxZoom\n */\n getMaxZoom() { return this.transform.maxZoom; }\n\n /**\n * Returns a {@link Point} representing pixel coordinates, relative to the map's `container`,\n * that correspond to the specified geographical location.\n *\n * @param {LngLatLike} lnglat The geographical location to project.\n * @returns {Point} The {@link Point} corresponding to `lnglat`, relative to the map's `container`.\n */\n project(lnglat: LngLatLike) {\n return this.transform.locationPoint(LngLat.convert(lnglat));\n }\n\n /**\n * Returns a {@link LngLat} representing geographical coordinates that correspond\n * to the specified pixel coordinates.\n *\n * @param {PointLike} point The pixel coordinates to unproject.\n * @returns {LngLat} The {@link LngLat} corresponding to `point`.\n * @see [Show polygon information on click](https://www.mapbox.com/mapbox-gl-js/example/polygon-popup-on-click/)\n */\n unproject(point: PointLike) {\n return this.transform.pointLocation(Point.convert(point));\n }\n\n /**\n * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.\n */\n isMoving(): boolean {\n return this._moving ||\n this.dragPan.isActive() ||\n this.dragRotate.isActive() ||\n this.scrollZoom.isActive();\n }\n\n /**\n * Returns true if the map is zooming due to a camera animation or user gesture.\n */\n isZooming(): boolean {\n return this._zooming ||\n this.scrollZoom.isZooming();\n }\n\n /**\n * Returns true if the map is rotating due to a camera animation or user gesture.\n */\n isRotating(): boolean {\n return this._rotating ||\n this.dragRotate.isActive();\n }\n\n /**\n * Adds a listener for events of a specified type.\n *\n * @method\n * @name on\n * @memberof Map\n * @instance\n * @param {string} type The event type to add a listen for.\n * @param {Function} 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 * @returns {Map} `this`\n */\n\n /**\n * Adds a listener for events of a specified type occurring on features in a specified style layer.\n *\n * @param {string} 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 {string} layerId The ID of a style layer. 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 {Function} listener The function to be called when the event is fired.\n * @returns {Map} `this`\n */\n on(type: MapEvent, layerId: any, listener: any) {\n if (listener === undefined) {\n return super.on(type, layerId);\n }\n\n const delegatedListener = (() => {\n if (type === 'mouseenter' || type === 'mouseover') {\n let mousein = false;\n const mousemove = (e) => {\n const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : [];\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 {layer: layerId, listener, delegates: {mousemove, mouseout}};\n } else if (type === 'mouseleave' || type === 'mouseout') {\n let mousein = false;\n const mousemove = (e) => {\n const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : [];\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 {layer: layerId, listener, delegates: {mousemove, mouseout}};\n } else {\n const delegate = (e) => {\n const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : [];\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 {layer: layerId, listener, delegates: {[type]: delegate}};\n }\n })();\n\n this._delegatedListeners = this._delegatedListeners || {};\n this._delegatedListeners[type] = this._delegatedListeners[type] || [];\n this._delegatedListeners[type].push(delegatedListener);\n\n for (const event in delegatedListener.delegates) {\n this.on((event: any), delegatedListener.delegates[event]);\n }\n\n return this;\n }\n\n /**\n * Removes an event listener previously added with `Map#on`.\n *\n * @method\n * @name off\n * @memberof Map\n * @instance\n * @param {string} type The event type previously used to install the listener.\n * @param {Function} listener The function previously installed as a listener.\n * @returns {Map} `this`\n */\n\n /**\n * Removes an event listener for layer-specific events previously added with `Map#on`.\n *\n * @param {string} type The event type previously used to install the listener.\n * @param {string} layerId The layer ID previously used to install the listener.\n * @param {Function} listener The function previously installed as a listener.\n * @returns {Map} `this`\n */\n off(type: MapEvent, layerId: any, listener: any) {\n if (listener === undefined) {\n return super.off(type, layerId);\n }\n\n if (this._delegatedListeners && this._delegatedListeners[type]) {\n const listeners = this._delegatedListeners[type];\n for (let i = 0; i < listeners.length; i++) {\n const delegatedListener = listeners[i];\n if (delegatedListener.layer === layerId && delegatedListener.listener === listener) {\n for (const event in delegatedListener.delegates) {\n this.off((event: any), delegatedListener.delegates[event]);\n }\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n\n return this;\n }\n\n /**\n * Returns an array of [GeoJSON](http://geojson.org/)\n * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)\n * representing visible features that satisfy the query parameters.\n *\n * @param {PointLike|Array} [geometry] - 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 * @param {Object} [options]\n * @param {Array} [options.layers] An array of style layer IDs 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 * @param {Array} [options.filter] A [filter](https://www.mapbox.com/mapbox-gl-js/style-spec/#other-filter)\n * to limit query results.\n * @param {boolean} [options.validate=true] Whether to check if the [options.filter] conforms to the Mapbox GL 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 * @returns {Array} An array of [GeoJSON](http://geojson.org/)\n * [feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).\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 * Features from layers whose `visibility` property is `\"none\"`, or from layers whose zoom range excludes the\n * current zoom level are not included. Symbol features that have been hidden due to text or icon collision are\n * not included. 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 antimeridian 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 * var features = map.queryRenderedFeatures(\n * [20, 35],\n * { layers: ['my-layer-name'] }\n * );\n *\n * @example\n * // Find all features within a static bounding box\n * var features = map.queryRenderedFeatures(\n * [[10, 20], [30, 50]],\n * { layers: ['my-layer-name'] }\n * );\n *\n * @example\n * // Find all features within a bounding box around a point\n * var width = 10;\n * var height = 20;\n * var 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 * @example\n * // Query all rendered features from a single layer\n * var features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });\n * @see [Get features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/)\n * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)\n */\n queryRenderedFeatures(geometry?: PointLike | [PointLike, PointLike], options?: Object) {\n // The first parameter can be omitted entirely, making this effectively an overloaded method\n // with two signatures:\n //\n // queryRenderedFeatures(geometry: PointLike | [PointLike, PointLike], options?: Object)\n // queryRenderedFeatures(options?: Object)\n //\n // There no way to express that in a way that's compatible with both flow and documentation.js.\n // Related: https://github.com/facebook/flow/issues/1556\n\n if (!this.style) {\n return [];\n }\n\n if (options === undefined && geometry !== undefined && !(geometry instanceof Point) && !Array.isArray(geometry)) {\n options = (geometry: Object);\n geometry = undefined;\n }\n\n options = options || {};\n geometry = geometry || [[0, 0], [this.transform.width, this.transform.height]];\n\n let queryGeometry;\n if (geometry instanceof Point || typeof geometry[0] === 'number') {\n queryGeometry = [Point.convert(geometry)];\n } else {\n const tl = Point.convert(geometry[0]);\n const br = Point.convert(geometry[1]);\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 [GeoJSON](http://geojson.org/)\n * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)\n * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.\n *\n * @param {string} sourceId The ID of the vector tile or GeoJSON source to query.\n * @param {Object} [parameters]\n * @param {string} [parameters.sourceLayer] The name of the vector tile layer to query. *For vector tile\n * sources, this parameter is required.* For GeoJSON sources, it is ignored.\n * @param {Array} [parameters.filter] A [filter](https://www.mapbox.com/mapbox-gl-js/style-spec/#other-filter)\n * to limit query results.\n * @param {boolean} [parameters.validate=true] Whether to check if the [parameters.filter] conforms to the Mapbox GL 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 * @returns {Array} An array of [GeoJSON](http://geojson.org/)\n * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).\n *\n * In contrast to {@link Map#queryRenderedFeatures}, this function\n * 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 * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)\n * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)\n */\n querySourceFeatures(sourceId: string, parameters: ?{sourceLayer: ?string, filter: ?Array, validate?: boolean}) {\n return this.style.querySourceFeatures(sourceId, parameters);\n }\n\n /**\n * Updates the map's Mapbox style object with a new value. If a style already is set and options.diff is true,\n * this compares the style against the map's current state and performs only the changes necessary to make\n * the map style match the desired state.\n *\n * @param style A JSON object conforming to the schema described in the\n * [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to such JSON.\n * @param {Object} [options]\n * @param {boolean} [options.diff=true] If false, force a 'full' update, removing the current style\n * and building the given one instead of attempting a diff-based update.\n * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS\n * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges.\n * In these ranges, 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 * @returns {Map} `this`\n * @see [Change a map's style](https://www.mapbox.com/mapbox-gl-js/example/setstyle/)\n */\n setStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) {\n options = extend({}, { localIdeographFontFamily: this._localIdeographFontFamily}, 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 _updateStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) {\n if (this.style) {\n this.style.setEventedParent(null);\n this.style._remove();\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);\n } else {\n this.style.loadJSON(style);\n }\n\n return this;\n }\n\n _diffStyle(style: StyleSpecification | string, options?: {diff?: boolean} & StyleOptions) {\n if (typeof style === 'string') {\n const url = this._requestManager.normalizeStyleURL(style);\n const request = this._requestManager.transformRequest(url, ResourceType.Style);\n getJSON(request, (error: ?Error, json: ?Object) => {\n if (error) {\n this.fire(new ErrorEvent(error));\n } else if (json) {\n this._updateDiff(json, options);\n }\n });\n } else if (typeof style === 'object') {\n this._updateDiff(style, options);\n }\n }\n\n _updateDiff(style: StyleSpecification, options?: {diff?: boolean} & StyleOptions) {\n try {\n if (this.style.setState(style)) {\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 Mapbox style object, which can be used to recreate the map's style.\n *\n * @returns {Object} The map's style object.\n */\n getStyle() {\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 {boolean} A Boolean indicating whether the style is fully loaded.\n */\n isStyleLoaded() {\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 * @param {string} id The ID of the source to add. Must not conflict with existing sources.\n * @param {Object} source The source object, conforming to the\n * Mapbox Style Specification's [source definition](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or\n * {@link CanvasSourceOptions}.\n * @fires source.add\n * @returns {Map} `this`\n * @see [Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/)\n * @see [Style circles using data-driven styling](https://www.mapbox.com/mapbox-gl-js/example/data-driven-circle-colors/)\n * @see [Set a point after Geocoder result](https://www.mapbox.com/mapbox-gl-js/example/point-from-geocoder-result/)\n */\n addSource(id: string, source: SourceSpecification) {\n this.style.addSource(id, source);\n return this._update(true);\n }\n\n /**\n * Returns a Boolean indicating whether the source is loaded.\n *\n * @param {string} id The ID of the source to be checked.\n * @returns {boolean} A Boolean indicating whether the source is loaded.\n */\n isSourceLoaded(id: string) {\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 * Returns a Boolean indicating whether all tiles in the viewport from all sources on\n * the style are loaded.\n *\n * @returns {boolean} A Boolean indicating whether all tiles are loaded.\n */\n\n areTilesLoaded() {\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 * Adds a [custom source type](#Custom Sources), making it available for use with\n * {@link Map#addSource}.\n * @private\n * @param {string} name The name of the source type; source definition objects use this name in the `{type: ...}` field.\n * @param {Function} SourceType A {@link Source} constructor.\n * @param {Function} callback Called when the source type is ready or with an error argument if there is an error.\n */\n addSourceType(name: string, SourceType: any, callback: Function) {\n return this.style.addSourceType(name, SourceType, callback);\n }\n\n /**\n * Removes a source from the map's style.\n *\n * @param {string} id The ID of the source to remove.\n * @returns {Map} `this`\n */\n removeSource(id: string) {\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 * @param {string} id The ID of the source to get.\n * @returns {?Object} The style source with the specified ID, or `undefined`\n * if the ID corresponds to no existing sources.\n * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n * @see [Animate a point](https://www.mapbox.com/mapbox-gl-js/example/animate-point-along-line/)\n * @see [Add live realtime data](https://www.mapbox.com/mapbox-gl-js/example/live-geojson/)\n */\n getSource(id: string) {\n return this.style.getSource(id);\n }\n\n /**\n * Add an image to the style. This image can be used in `icon-image`,\n * `background-pattern`, `fill-pattern`, and `line-pattern`. An\n * {@link Map#error} event will be fired if there is not enough space in the\n * sprite to add this image.\n *\n * @see [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)\n * @see [Add a generated icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image-generated/)\n * @param id The ID of the image.\n * @param image The image as an `HTMLImageElement`, `ImageData`, or object with `width`, `height`, and `data`\n * properties with the same format as `ImageData`.\n * @param options\n * @param options.pixelRatio The ratio of pixels in the image to physical pixels on the screen\n * @param options.sdf Whether the image should be interpreted as an SDF image\n */\n addImage(id: string,\n image: HTMLImageElement | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface,\n {pixelRatio = 1, sdf = false}: {pixelRatio?: number, sdf?: boolean} = {}) {\n\n const version = 0;\n\n if (image instanceof HTMLImageElement) {\n const {width, height, data} = browser.getImageData(image);\n this.style.addImage(id, { data: new RGBAImage({width, height}, data), pixelRatio, 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`, ' +\n 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));\n } else {\n const {width, height, data} = image;\n const userImage = ((image: any): StyleImageInterface);\n\n this.style.addImage(id, {\n data: new RGBAImage({width, height}, new Uint8Array(data)),\n pixelRatio,\n sdf,\n version,\n userImage\n });\n\n if (userImage.onAdd) {\n userImage.onAdd(this, id);\n }\n }\n }\n\n /**\n * Update an existing style image. This image can be used in `icon-image`,\n * `background-pattern`, `fill-pattern`, and `line-pattern`.\n *\n * @param id The ID of the image.\n * @param image The image as an `HTMLImageElement`, `ImageData`, or object with `width`, `height`, and `data`\n * properties with the same format as `ImageData`.\n */\n updateImage(id: string,\n image: HTMLImageElement | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface) {\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\n const imageData = image instanceof HTMLImageElement ? browser.getImageData(image) : 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`, ' +\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);\n existingImage.data.replace(data, copy);\n\n this.style.updateImage(id, existingImage);\n }\n\n /**\n * Define whether the image has been added or not\n *\n * @param id The ID of the image.\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 the style (such as one used by `icon-image` or `background-pattern`).\n *\n * @param id The ID of the image.\n */\n removeImage(id: string) {\n this.style.removeImage(id);\n }\n\n /**\n * Load an image from an external URL for use with `Map#addImage`. External\n * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).\n *\n * @param {string} url The URL of the image file. Image file must be in png, webp, or jpg format.\n * @param {Function} callback Expecting `callback(error, data)`. Called when the image has loaded or with an error argument if there is an error.\n * @see [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)\n */\n loadImage(url: string, callback: Function) {\n getImage(this._requestManager.transformRequest(url, ResourceType.Image), callback);\n }\n\n /**\n * Returns an Array of strings containing the names of all sprites/images currently available in the map\n *\n * @returns {Array} An Array of strings containing the names of all sprites/images currently available in the map\n *\n */\n listImages() {\n return this.style.listImages();\n }\n\n /**\n * Adds a [Mapbox style layer](https://www.mapbox.com/mapbox-gl-style-spec/#layers)\n * to the map's style.\n *\n * A layer defines styling for data from a specified source.\n *\n * @param {Object | CustomLayerInterface} layer The style layer to add, conforming to the Mapbox Style Specification's\n * [layer definition](https://www.mapbox.com/mapbox-gl-style-spec/#layers).\n * @param {string} [beforeId] The ID of an existing layer to insert the new layer before.\n * If this argument is omitted, the layer will be appended to the end of the layers array.\n * @returns {Map} `this`\n * @see [Create and style clusters](https://www.mapbox.com/mapbox-gl-js/example/cluster/)\n * @see [Add a vector tile source](https://www.mapbox.com/mapbox-gl-js/example/vector-source/)\n * @see [Add a WMS source](https://www.mapbox.com/mapbox-gl-js/example/wms/)\n */\n addLayer(layer: LayerSpecification | CustomLayerInterface, beforeId?: string) {\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 {string} id The ID of the layer to move.\n * @param {string} [beforeId] The ID of an existing layer to insert the new layer before.\n * If this argument is omitted, the layer will be appended to the end of the layers array.\n * @returns {Map} `this`\n */\n moveLayer(id: string, beforeId?: string) {\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 * If no such layer exists, an `error` event is fired.\n *\n * @param {string} id id of the layer to remove\n * @fires error\n */\n removeLayer(id: string) {\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 {string} id The ID of the layer to get.\n * @returns {?Object} The layer with the specified ID, or `undefined`\n * if the ID corresponds to no existing layers.\n * @see [Filter symbols by toggling a list](https://www.mapbox.com/mapbox-gl-js/example/filter-markers/)\n * @see [Filter symbols by text input](https://www.mapbox.com/mapbox-gl-js/example/filter-markers-by-input/)\n */\n getLayer(id: string) {\n return this.style.getLayer(id);\n }\n\n /**\n * Sets the filter for the specified style layer.\n *\n * @param {string} layerId The ID of the layer to which the filter will be applied.\n * @param {Array | null | undefined} filter The filter, conforming to the Mapbox Style Specification's\n * [filter definition](https://www.mapbox.com/mapbox-gl-js/style-spec/#other-filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer.\n * @param {Object} [options]\n * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL 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 * @returns {Map} `this`\n * @example\n * map.setFilter('my-layer', ['==', 'name', 'USA']);\n * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)\n * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)\n * @see [Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/)\n */\n setFilter(layerId: string, filter: ?FilterSpecification, options: StyleSetterOptions = {}) {\n this.style.setFilter(layerId, filter, options);\n return this._update(true);\n }\n\n /**\n * Sets the zoom extent for the specified style layer.\n *\n * @param {string} layerId The ID of the layer to which the zoom extent will be applied.\n * @param {number} minzoom The minimum zoom to set (0-24).\n * @param {number} maxzoom The maximum zoom to set (0-24).\n * @returns {Map} `this`\n * @example\n * map.setLayerZoomRange('my-layer', 2, 5);\n */\n setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number) {\n this.style.setLayerZoomRange(layerId, minzoom, maxzoom);\n return this._update(true);\n }\n\n /**\n * Returns the filter applied to the specified style layer.\n *\n * @param {string} layerId The ID of the style layer whose filter to get.\n * @returns {Array} The layer's filter.\n */\n getFilter(layerId: string) {\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 {string} layerId The ID of the layer to set the paint property in.\n * @param {string} 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 [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/).\n * @param {Object} [options]\n * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL 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 * @returns {Map} `this`\n * @example\n * map.setPaintProperty('my-layer', 'fill-color', '#faafee');\n * @see [Change a layer's color with buttons](https://www.mapbox.com/mapbox-gl-js/example/color-switcher/)\n * @see [Adjust a layer's opacity](https://www.mapbox.com/mapbox-gl-js/example/adjust-layer-opacity/)\n * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {\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 {string} layerId The ID of the layer to get the paint property from.\n * @param {string} 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 {string} layerId The ID of the layer to set the layout property in.\n * @param {string} 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 [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/).\n * @param {Object} [options]\n * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL 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 * @returns {Map} `this`\n * @example\n * map.setLayoutProperty('my-layer', 'visibility', 'none');\n */\n setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {\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 {string} layerId The ID of the layer to get the layout property from.\n * @param {string} 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 any combination of light values.\n *\n * @param light Light properties to set. Must conform to the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#light).\n * @param {Object} [options]\n * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL 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 * @returns {Map} `this`\n */\n setLight(light: LightSpecification, options: StyleSetterOptions = {}) {\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 {Object} light Light properties of the style.\n */\n getLight() {\n return this.style.getLight();\n }\n\n /**\n * Sets the state of a feature. The `state` object is merged in with the existing state of the feature.\n * Features are identified by their `id` attribute, which must be an integer or a string that can be\n * cast to an integer.\n *\n * @param {Object} feature Feature identifier. Feature objects returned from\n * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.\n * @param {string | number} feature.id Unique id of the feature.\n * @param {string} feature.source The Id of the vector source or GeoJSON source for the feature.\n * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, the sourceLayer is\n * required.*\n * @param {Object} state A set of key-value pairs. The values should be valid JSON types.\n *\n * This method requires the `feature.id` attribute on data sets. For GeoJSON sources without\n * feature ids, set the `generateId` option in the `GeoJSONSourceSpecification` to auto-assign them. This\n * option assigns ids based on a feature's index in the source data. If you change feature data using\n * `map.getSource('some id').setData(..)`, you may need to re-apply state taking into account updated `id` values.\n */\n setFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }, state: Object) {\n this.style.setFeatureState(feature, state);\n return this._update();\n }\n\n /**\n * Removes feature state, setting it back to the default behavior. If only\n * source is specified, removes all states of that source. If\n * target.id is also specified, removes all keys for that feature's state.\n * If key is also specified, removes that key from that feature's state.\n * Features are identified by their `id` attribute, which must be an integer or a string that can be\n * cast to an integer.\n * @param {Object} target Identifier of where to set state: 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 {string | number} target.id (optional) Unique id of the feature. Optional if key is not specified.\n * @param {string} target.source The Id of the vector source or GeoJSON source for the feature.\n * @param {string} [target.sourceLayer] (optional) *For vector tile sources, the sourceLayer is\n * required.*\n * @param {string} key (optional) The key in the feature state to reset.\n */\n removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, key?: string) {\n this.style.removeFeatureState(target, key);\n return this._update();\n }\n\n /**\n * Gets the state of a feature.\n * Features are identified by their `id` attribute, which must be an integer or a string that can be\n * cast to an integer.\n *\n * @param {Object} feature Feature identifier. Feature objects returned from\n * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.\n * @param {string | number} feature.id Unique id of the feature.\n * @param {string} feature.source The Id of the vector source or GeoJSON source for the feature.\n * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, the sourceLayer is\n * required.*\n *\n * @returns {Object} The state of the feature.\n */\n getFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }): any {\n return this.style.getFeatureState(feature);\n }\n\n /**\n * Returns the map's containing HTML element.\n *\n * @returns {HTMLElement} The map's container.\n */\n getContainer() {\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 {HTMLElement} The container of the map's ``.\n * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n */\n getCanvasContainer() {\n return this._canvasContainer;\n }\n\n /**\n * Returns the map's `` element.\n *\n * @returns {HTMLCanvasElement} The map's `` element.\n * @see [Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/)\n * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)\n */\n getCanvas() {\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 _detectMissingCSS(): void {\n const computedColor = window.getComputedStyle(this._missingCSSCanary).getPropertyValue('background-color');\n if (computedColor !== 'rgb(250, 128, 114)') {\n warnOnce('This page appears to be missing CSS declarations for ' +\n 'Mapbox GL JS, which may cause the map to display incorrectly. ' +\n 'Please ensure your page includes mapbox-gl.css, as described ' +\n 'in https://www.mapbox.com/mapbox-gl-js/api/.');\n }\n }\n\n _setupContainer() {\n const container = this._container;\n container.classList.add('mapboxgl-map');\n\n const missingCSSCanary = this._missingCSSCanary = DOM.create('div', 'mapboxgl-canary', container);\n missingCSSCanary.style.visibility = 'hidden';\n this._detectMissingCSS();\n\n const canvasContainer = this._canvasContainer = DOM.create('div', 'mapboxgl-canvas-container', container);\n if (this._interactive) {\n canvasContainer.classList.add('mapboxgl-interactive');\n }\n\n this._canvas = DOM.create('canvas', 'mapboxgl-canvas', canvasContainer);\n this._canvas.style.position = 'absolute';\n this._canvas.addEventListener('webglcontextlost', this._contextLost, false);\n this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false);\n this._canvas.setAttribute('tabindex', '0');\n this._canvas.setAttribute('aria-label', 'Map');\n\n const dimensions = this._containerDimensions();\n this._resizeCanvas(dimensions[0], dimensions[1]);\n\n const controlContainer = this._controlContainer = DOM.create('div', 'mapboxgl-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', `mapboxgl-ctrl-${positionName}`, controlContainer);\n });\n }\n\n _resizeCanvas(width: number, height: number) {\n const pixelRatio = window.devicePixelRatio || 1;\n\n // Request the required canvas size taking the pixelratio into account.\n this._canvas.width = pixelRatio * width;\n this._canvas.height = 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 const attributes = extend({}, isSupported.webGLContextAttributes, {\n failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat,\n preserveDrawingBuffer: this._preserveDrawingBuffer,\n antialias: this._antialias || false\n });\n\n const gl = this._canvas.getContext('webgl', attributes) ||\n this._canvas.getContext('experimental-webgl', attributes);\n\n if (!gl) {\n this.fire(new ErrorEvent(new Error('Failed to initialize WebGL')));\n return;\n }\n\n this.painter = new Painter(gl, this.transform);\n\n webpSupported.testSupport(gl);\n }\n\n _contextLost(event: *) {\n event.preventDefault();\n if (this._frame) {\n this._frame.cancel();\n this._frame = null;\n }\n this.fire(new Event('webglcontextlost', {originalEvent: event}));\n }\n\n _contextRestored(event: *) {\n this._setupPainter();\n this.resize();\n this._update();\n this.fire(new Event('webglcontextrestored', {originalEvent: event}));\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 {boolean} A Boolean indicating whether the map is fully loaded.\n */\n loaded() {\n return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded();\n }\n\n /**\n * Update this map's style and sources, and re-render the map.\n *\n * @param {boolean} updateStyle mark the map's style for reprocessing as\n * well as its sources\n * @returns {Map} this\n * @private\n */\n _update(updateStyle?: boolean) {\n if (!this.style) return this;\n\n this._styleDirty = this._styleDirty || updateStyle;\n this._sourcesDirty = true;\n this.triggerRepaint();\n\n return this;\n }\n\n /**\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 * @returns An id that can be used to cancel the callback\n * @private\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 * Call when a (re-)render of the map is required:\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 * @returns {Map} this\n * @private\n */\n _render() {\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();\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: this._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 this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, this._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: this._fadeDuration\n });\n\n this.fire(new Event('render'));\n\n if (this.loaded() && !this._loaded) {\n this._loaded = true;\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 if (this._sourcesDirty || this._repaint || this._styleDirty || this._placementDirty) {\n this.triggerRepaint();\n } else if (!this.isMoving() && this.loaded()) {\n this.fire(new Event('idle'));\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._frame) {\n this._frame.cancel();\n this._frame = null;\n }\n this._renderTaskQueue.clear();\n this.setStyle(null);\n if (typeof window !== 'undefined') {\n window.removeEventListener('resize', this._onWindowResize, false);\n window.removeEventListener('online', this._onWindowOnline, false);\n }\n\n const extension = this.painter.context.gl.getExtension('WEBGL_lose_context');\n if (extension) extension.loseContext();\n removeNode(this._canvasContainer);\n removeNode(this._controlContainer);\n removeNode(this._missingCSSCanary);\n this._container.classList.remove('mapboxgl-map');\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 */\n triggerRepaint() {\n if (this.style && !this._frame) {\n this._frame = browser.frame(() => {\n this._frame = null;\n this._render();\n });\n }\n }\n\n _onWindowOnline() {\n this._update();\n }\n\n _onWindowResize() {\n if (this._trackResize) {\n this.resize()._update();\n }\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 * @name showTileBoundaries\n * @type {boolean}\n * @instance\n * @memberof Map\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 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 * @name showCollisionBoxes\n * @type {boolean}\n * @instance\n * @memberof Map\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 * @name showOverdraw\n * @type {boolean}\n * @instance\n * @memberof Map\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 * @name repaint\n * @type {boolean}\n * @instance\n * @memberof Map\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 // for cache browser tests\n _setCacheLimits(limit: number, checkThreshold: number) {\n setCacheLimits(limit, checkThreshold);\n }\n\n /**\n * The version of Mapbox GL JS in use as specified in package.json, CHANGELOG.md, and the GitHub release.\n *\n * @name version\n * @instance\n * @memberof Map\n * @var {string} version\n */\n\n get version(): string { return version; }\n}\n\nexport default Map;\n\nfunction removeNode(node) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n}\n\n/**\n * Interface for interactive controls added to the map. This is an\n * specification for implementers to model: it is not\n * an exported method or class.\n *\n * Controls must implement `onAdd` and `onRemove`, and must own an\n * element, which is often a `div` element. To use Mapbox GL JS's\n * default control styling, add the `mapboxgl-ctrl` class to your control's\n * node.\n *\n * @interface IControl\n * @example\n * // Control implemented as ES6 class\n * class HelloWorldControl {\n * onAdd(map) {\n * this._map = map;\n * this._container = document.createElement('div');\n * this._container.className = 'mapboxgl-ctrl';\n * this._container.textContent = 'Hello, world';\n * return this._container;\n * }\n *\n * onRemove() {\n * this._container.parentNode.removeChild(this._container);\n * this._map = undefined;\n * }\n * }\n *\n * // Control implemented as ES5 prototypical class\n * function HelloWorldControl() { }\n *\n * HelloWorldControl.prototype.onAdd = function(map) {\n * this._map = map;\n * this._container = document.createElement('div');\n * this._container.className = 'mapboxgl-ctrl';\n * this._container.textContent = 'Hello, world';\n * return this._container;\n * };\n *\n * HelloWorldControl.prototype.onRemove = function () {\n * this._container.parentNode.removeChild(this._container);\n * this._map = undefined;\n * };\n */\n\n/**\n * Register a control on the map and give it a chance to register event listeners\n * and resources. This method is called by {@link Map#addControl}\n * internally.\n *\n * @function\n * @memberof IControl\n * @instance\n * @name onAdd\n * @param {Map} map the Map this control will be added to\n * @returns {HTMLElement} The control's container element. This should\n * be created by the control and returned by onAdd without being attached\n * to the DOM: the map will insert the control's element into the DOM\n * as necessary.\n */\n\n/**\n * Unregister a control on the map and give it a chance to detach event listeners\n * and resources. This method is called by {@link Map#removeControl}\n * internally.\n *\n * @function\n * @memberof IControl\n * @instance\n * @name onRemove\n * @param {Map} map the Map this control will be removed from\n * @returns {undefined} there is no required return value for this method\n */\n\n/**\n * Optionally provide a default position for this control. If this method\n * is implemented and {@link Map#addControl} is called without the `position`\n * parameter, the value returned by getDefaultPosition will be used as the\n * control's position.\n *\n * @function\n * @memberof IControl\n * @instance\n * @name getDefaultPosition\n * @returns {string} a control position, one of the values valid in addControl.\n */\n\n/**\n * A [`Point` geometry](https://github.com/mapbox/point-geometry) object, which has\n * `x` and `y` properties representing screen coordinates in pixels.\n *\n * @typedef {Object} Point\n */\n\n/**\n * A {@link Point} or an array of two numbers representing `x` and `y` screen coordinates in pixels.\n *\n * @typedef {(Point | Array)} PointLike\n */\n","// @flow\n\nimport DOM from '../../util/dom';\nimport { extend, bindAll } from '../../util/util';\nimport DragRotateHandler from '../handler/drag_rotate';\n\nimport type Map from '../map';\n\ntype Options = {\n showCompass?: boolean,\n showZoom?: boolean,\n visualizePitch?: boolean\n};\n\nconst defaultOptions: Options = {\n showCompass: true,\n showZoom: true,\n visualizePitch: false\n};\n\n/**\n * A `NavigationControl` control contains zoom buttons and a compass.\n *\n * @implements {IControl}\n * @param {Object} [options]\n * @param {Boolean} [options.showCompass=true] If `true` the compass button is included.\n * @param {Boolean} [options.showZoom=true] If `true` the zoom-in and zoom-out buttons are included.\n * @param {Boolean} [options.visualizePitch=false] If `true` the pitch is visualized by rotating X-axis of compass.\n * @example\n * var nav = new mapboxgl.NavigationControl();\n * map.addControl(nav, 'top-left');\n * @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/)\n * @see [Add a third party vector tile source](https://www.mapbox.com/mapbox-gl-js/example/third-party/)\n */\nclass NavigationControl {\n _map: Map;\n options: Options;\n _container: HTMLElement;\n _zoomInButton: HTMLElement;\n _zoomOutButton: HTMLElement;\n _compass: HTMLElement;\n _compassArrow: HTMLElement;\n _handler: DragRotateHandler;\n\n constructor(options: Options) {\n this.options = extend({}, defaultOptions, options);\n\n this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-group');\n this._container.addEventListener('contextmenu', (e) => e.preventDefault());\n\n if (this.options.showZoom) {\n bindAll([\n '_updateZoomButtons'\n ], this);\n this._zoomInButton = this._createButton('mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-in', 'Zoom in', () => this._map.zoomIn());\n this._zoomOutButton = this._createButton('mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-out', 'Zoom out', () => this._map.zoomOut());\n }\n if (this.options.showCompass) {\n bindAll([\n '_rotateCompassArrow'\n ], this);\n this._compass = this._createButton('mapboxgl-ctrl-icon mapboxgl-ctrl-compass', 'Reset bearing to north', () => {\n if (this.options.visualizePitch) {\n this._map.resetNorthPitch();\n } else {\n this._map.resetNorth();\n }\n });\n this._compassArrow = DOM.create('span', 'mapboxgl-ctrl-compass-arrow', this._compass);\n }\n }\n\n _updateZoomButtons() {\n const zoom = this._map.getZoom();\n if (zoom === this._map.getMaxZoom()) {\n this._zoomInButton.classList.add('mapboxgl-ctrl-icon-disabled');\n } else {\n this._zoomInButton.classList.remove('mapboxgl-ctrl-icon-disabled');\n }\n if (zoom === this._map.getMinZoom()) {\n this._zoomOutButton.classList.add('mapboxgl-ctrl-icon-disabled');\n } else {\n this._zoomOutButton.classList.remove('mapboxgl-ctrl-icon-disabled');\n }\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._compassArrow.style.transform = rotate;\n }\n\n onAdd(map: Map) {\n this._map = map;\n if (this.options.showZoom) {\n this._map.on('zoom', this._updateZoomButtons);\n this._updateZoomButtons();\n }\n if (this.options.showCompass) {\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 DragRotateHandler(map, {button: 'left', element: this._compass});\n DOM.addEventListener(this._compass, 'mousedown', this._handler.onMouseDown);\n DOM.addEventListener(this._compass, 'touchstart', this._handler.onMouseDown, { passive: false });\n this._handler.enable();\n }\n return this._container;\n }\n\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 DOM.removeEventListener(this._compass, 'mousedown', this._handler.onMouseDown);\n DOM.removeEventListener(this._compass, 'touchstart', this._handler.onMouseDown, { passive: false });\n this._handler.disable();\n delete this._handler;\n }\n\n delete this._map;\n }\n\n _createButton(className: string, ariaLabel: string, fn: () => mixed) {\n const a = DOM.create('button', className, this._container);\n a.type = 'button';\n a.title = ariaLabel;\n a.setAttribute('aria-label', ariaLabel);\n a.addEventListener('click', fn);\n return a;\n }\n}\n\nexport default NavigationControl;\n","// @flow\n\nimport 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 *\n * @private\n */\nexport default function(lngLat: LngLat, priorPos: ?Point, transform: Transform): LngLat {\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 return lngLat;\n}\n","// @flow\n\nexport type Anchor =\n | 'center'\n | 'top'\n | 'bottom'\n | 'left'\n | 'right'\n | 'top-left'\n | 'top-right'\n | 'bottom-left'\n | 'bottom-right';\n\nexport const anchorTranslate: {[Anchor]: string} = {\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: Anchor, prefix: string) {\n const classList = element.classList;\n for (const key in anchorTranslate) {\n classList.remove(`mapboxgl-${prefix}-anchor-${key}`);\n }\n classList.add(`mapboxgl-${prefix}-anchor-${anchor}`);\n}\n","// @flow\n\nimport DOM from '../util/dom';\nimport window from '../util/window';\nimport LngLat from '../geo/lng_lat';\nimport Point from '@mapbox/point-geometry';\nimport smartWrap from '../util/smart_wrap';\nimport { bindAll, extend } from '../util/util';\nimport { type Anchor, anchorTranslate, applyAnchorClass } from './anchor';\nimport { Event, Evented } from '../util/evented';\nimport type Map from './map';\nimport type Popup from './popup';\nimport type {LngLatLike} from \"../geo/lng_lat\";\nimport type {MapMouseEvent, MapTouchEvent} from './events';\nimport type {PointLike} from '@mapbox/point-geometry';\n\ntype Options = {\n element?: HTMLElement,\n offset?: PointLike,\n anchor?: Anchor,\n color?: string,\n draggable?: boolean\n};\n\n/**\n * Creates a marker component\n * @param {Object} [options]\n * @param {HTMLElement} [options.element] DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.\n * @param {string} [options.anchor='center'] 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 * @param {PointLike} [options.offset] The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up.\n * @param {string} [options.color='#3FB1CE'] The color to use for the default marker if options.element is not provided. The default is light blue.\n * @param {boolean} [options.draggable=false] A boolean indicating whether or not a marker is able to be dragged to a new position on the map.\n * @example\n * var marker = new mapboxgl.Marker()\n * .setLngLat([30.5, 50.5])\n * .addTo(map);\n * @see [Add custom icons with Markers](https://www.mapbox.com/mapbox-gl-js/example/custom-marker-icons/)\n * @see [Create a draggable Marker](https://www.mapbox.com/mapbox-gl-js/example/drag-a-marker/)\n */\nexport default class Marker extends Evented {\n _map: Map;\n _anchor: Anchor;\n _offset: Point;\n _element: HTMLElement;\n _popup: ?Popup;\n _lngLat: LngLat;\n _pos: ?Point;\n _color: ?string;\n _defaultMarker: boolean;\n _draggable: boolean;\n _state: 'inactive' | 'pending' | 'active'; // used for handling drag events\n _positionDelta: ?number;\n\n constructor(options?: Options, legacyOptions?: Options) {\n super();\n // For backward compatibility -- the constructor used to accept the element as a\n // required first argument, before it was made optional.\n if (options instanceof window.HTMLElement || legacyOptions) {\n options = extend({element: options}, legacyOptions);\n }\n\n bindAll([\n '_update',\n '_onMove',\n '_onUp',\n '_addDragHandler',\n '_onMapClick'\n ], this);\n\n this._anchor = options && options.anchor || 'center';\n this._color = options && options.color || '#3FB1CE';\n this._draggable = options && options.draggable || false;\n this._state = 'inactive';\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 svg.setAttributeNS(null, 'display', 'block');\n svg.setAttributeNS(null, 'height', '41px');\n svg.setAttributeNS(null, 'width', '27px');\n svg.setAttributeNS(null, 'viewBox', '0 0 27 41');\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 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('mapboxgl-marker');\n this._element.addEventListener('dragstart', (e: DragEvent) => {\n e.preventDefault();\n });\n applyAnchorClass(this._element, this._anchor, 'marker');\n\n this._popup = null;\n }\n\n /**\n * Attaches the marker to a map\n * @param {Map} map\n * @returns {Marker} `this`\n */\n addTo(map: Map) {\n this.remove();\n this._map = map;\n map.getCanvasContainer().appendChild(this._element);\n map.on('move', this._update);\n map.on('moveend', this._update);\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 propogated 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 * var marker = new mapboxgl.Marker().addTo(map);\n * marker.remove();\n * @returns {Marker} `this`\n */\n remove() {\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('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 {LngLat}\n */\n getLngLat() {\n return this._lngLat;\n }\n\n /**\n * Set the marker's geographical position and move it.\n * @returns {Marker} `this`\n */\n setLngLat(lnglat: LngLatLike) {\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 {HTMLElement} element\n */\n getElement() {\n return this._element;\n }\n\n /**\n * Binds a Popup to the Marker\n * @param popup an instance of the `Popup` class. If undefined or null, any popup\n * set on this `Marker` instance is unset\n * @returns {Marker} `this`\n */\n setPopup(popup: ?Popup) {\n if (this._popup) {\n this._popup.remove();\n this._popup = null;\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.sqrt(Math.pow(markerRadius, 2) / 2);\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 } : this._offset;\n }\n this._popup = popup;\n if (this._lngLat) this._popup.setLngLat(this._lngLat);\n }\n\n return this;\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: any)))) {\n this.togglePopup();\n }\n }\n\n /**\n * Returns the Popup instance that is bound to the Marker\n * @returns {Popup} popup\n */\n getPopup() {\n return this._popup;\n }\n\n /**\n * Opens or closes the bound popup, depending on the current state\n * @returns {Marker} `this`\n */\n togglePopup() {\n const popup = this._popup;\n\n if (!popup) return this;\n else if (popup.isOpen()) popup.remove();\n else popup.addTo(this._map);\n return this;\n }\n\n _update(e?: {type: 'move' | 'moveend'}) {\n if (!this._map) return;\n\n if (this._map.transform.renderWorldCopies) {\n this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform);\n }\n\n this._pos = this._map.project(this._lngLat)._add(this._offset);\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 (!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)`);\n }\n\n /**\n * Get the marker's offset.\n * @returns {Point}\n */\n getOffset() {\n return this._offset;\n }\n\n /**\n * Sets the offset of the marker\n * @param {PointLike} offset The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up.\n * @returns {Marker} `this`\n */\n setOffset(offset: PointLike) {\n this._offset = Point.convert(offset);\n this._update();\n return this;\n }\n\n _onMove(e: MapMouseEvent | MapTouchEvent) {\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\n /**\n * Fired when dragging starts\n *\n * @event dragstart\n * @memberof Marker\n * @instance\n * @type {Object}\n * @property {Marker} marker object that is being dragged\n */\n this.fire(new Event('dragstart'));\n }\n\n /**\n * Fired while dragging\n *\n * @event drag\n * @memberof Marker\n * @instance\n * @type {Object}\n * @property {Marker} marker object that is being dragged\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._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 /**\n * Fired when the marker is finished being dragged\n *\n * @event dragend\n * @memberof Marker\n * @instance\n * @type {Object}\n * @property {Marker} marker object that was dragged\n */\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: 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._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 {boolean} [shouldBeDraggable=false] Turns drag functionality on/off\n * @returns {Marker} `this`\n */\n setDraggable(shouldBeDraggable: boolean) {\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 {boolean}\n */\n isDraggable() {\n return this._draggable;\n }\n}\n","// @flow\n\nimport { Event, Evented } from '../../util/evented';\nimport DOM from '../../util/dom';\nimport window from '../../util/window';\nimport { extend, bindAll, warnOnce } from '../../util/util';\nimport assert from 'assert';\nimport LngLat from '../../geo/lng_lat';\nimport Marker from '../marker';\n\nimport type Map from '../map';\nimport type { AnimationOptions, CameraOptions } from '../camera';\n\ntype Options = {\n positionOptions?: PositionOptions,\n fitBoundsOptions?: AnimationOptions & CameraOptions,\n trackUserLocation?: boolean,\n showUserLocation?: boolean\n};\n\nconst defaultOptions: Options = {\n positionOptions: {\n enableHighAccuracy: false,\n maximumAge: 0,\n timeout: 6000 /* 6 sec */\n },\n fitBoundsOptions: {\n maxZoom: 15\n },\n trackUserLocation: false,\n showUserLocation: true\n};\nconst className = 'mapboxgl-ctrl';\n\nlet supportsGeolocation;\n\nfunction checkGeolocationSupport(callback) {\n if (supportsGeolocation !== undefined) {\n callback(supportsGeolocation);\n\n } else if (window.navigator.permissions !== undefined) {\n // navigator.permissions has incomplete browser support\n // http://caniuse.com/#feat=permissions-api\n // Test for the case where a browser disables Geolocation because of an\n // insecure origin\n window.navigator.permissions.query({ name: 'geolocation' }).then((p) => {\n supportsGeolocation = p.state !== 'denied';\n callback(supportsGeolocation);\n });\n\n } else {\n supportsGeolocation = !!window.navigator.geolocation;\n callback(supportsGeolocation);\n }\n}\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 not\n * be visible.\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 states:\n * * active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center.\n * * passive - the user's location dot automatically updates, but the map's camera does not.\n * * disabled\n *\n * @implements {IControl}\n * @param {Object} [options]\n * @param {Object} [options.positionOptions={enableHighAccuracy: false, timeout: 6000}] A Geolocation API [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object.\n * @param {Object} [options.fitBoundsOptions={maxZoom: 15}] A [`fitBounds`](#map#fitbounds) 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 * @param {Object} [options.trackUserLocation=false] If `true` the Geolocate Control becomes a toggle button and when active the map will receive updates to the user's location as it changes.\n * @param {Object} [options.showUserLocation=true] By default a dot will be shown on the map at the user's location. Set to `false` to disable.\n *\n * @example\n * map.addControl(new mapboxgl.GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * }));\n * @see [Locate the user](https://www.mapbox.com/mapbox-gl-js/example/locate-user/)\n */\nclass GeolocateControl extends Evented {\n _map: Map;\n options: Options;\n _container: HTMLElement;\n _dotElement: HTMLElement;\n _geolocateButton: HTMLElement;\n _geolocationWatchID: number;\n _timeoutId: ?TimeoutID;\n _watchState: string;\n _lastKnownPosition: any;\n _userLocationDotMarker: Marker;\n _setup: boolean; // set to true once the control has been setup\n\n constructor(options: Options) {\n super();\n this.options = extend({}, defaultOptions, options);\n\n bindAll([\n '_onSuccess',\n '_onError',\n '_finish',\n '_setupUI',\n '_updateCamera',\n '_updateMarker'\n ], this);\n }\n\n onAdd(map: Map) {\n this._map = map;\n this._container = DOM.create('div', `${className} ${className}-group`);\n checkGeolocationSupport(this._setupUI);\n return this._container;\n }\n\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: any);\n }\n\n // clear the marker from the map\n if (this.options.showUserLocation && this._userLocationDotMarker) {\n this._userLocationDotMarker.remove();\n }\n\n DOM.remove(this._container);\n this._map = (undefined: any);\n }\n\n _onSuccess(position: Position) {\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('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');\n break;\n case 'BACKGROUND':\n case 'BACKGROUND_ERROR':\n this._watchState = 'BACKGROUND';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');\n break;\n default:\n assert(false, `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('mapboxgl-user-location-dot-stale');\n }\n\n this.fire(new Event('geolocate', position));\n this._finish();\n }\n\n _updateCamera(position: Position) {\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\n this._map.fitBounds(center.toBounds(radius), options, {\n geolocateSource: true // tag this camera change so it won't cause the control to change to background state\n });\n }\n\n _updateMarker(position: ?Position) {\n if (position) {\n this._userLocationDotMarker.setLngLat([position.coords.longitude, position.coords.latitude]).addTo(this._map);\n } else {\n this._userLocationDotMarker.remove();\n }\n }\n\n _onError(error: PositionError) {\n if (this.options.trackUserLocation) {\n if (error.code === 1) {\n // PERMISSION_DENIED\n this._watchState = 'OFF';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error');\n\n if (this._geolocationWatchID !== undefined) {\n this._clearWatch();\n }\n } else {\n switch (this._watchState) {\n case 'WAITING_ACTIVE':\n this._watchState = 'ACTIVE_ERROR';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');\n break;\n case 'ACTIVE_LOCK':\n this._watchState = 'ACTIVE_ERROR';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n // turn marker grey\n break;\n case 'BACKGROUND':\n this._watchState = 'BACKGROUND_ERROR';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n // turn marker grey\n break;\n case 'ACTIVE_ERROR':\n break;\n default:\n assert(false, `Unexpected watchState ${this._watchState}`);\n }\n }\n }\n\n if (this._watchState !== 'OFF' && this.options.showUserLocation) {\n this._dotElement.classList.add('mapboxgl-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(supported: boolean) {\n if (supported === false) {\n warnOnce('Geolocation support is not available, the GeolocateControl will not be visible.');\n return;\n }\n this._container.addEventListener('contextmenu', (e: MouseEvent) => e.preventDefault());\n this._geolocateButton = DOM.create('button',\n `${className}-icon ${className}-geolocate`,\n this._container);\n this._geolocateButton.type = 'button';\n this._geolocateButton.setAttribute('aria-label', 'Geolocate');\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', 'mapboxgl-user-location-dot');\n\n this._userLocationDotMarker = new Marker(this._dotElement);\n\n if (this.options.trackUserLocation) this._watchState = 'OFF';\n }\n\n this._geolocateButton.addEventListener('click',\n this.trigger.bind(this));\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) => {\n if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK') {\n this._watchState = 'BACKGROUND';\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n\n this.fire(new Event('trackuserlocationend'));\n }\n });\n }\n }\n\n /**\n * Trigger a geolocation\n *\n * @returns {boolean} Returns `false` if called before control was added to a map, otherwise returns `true`.\n */\n trigger() {\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 this._watchState = 'OFF';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');\n this._geolocateButton.classList.remove('mapboxgl-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('mapboxgl-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 break;\n default:\n assert(false, `Unexpected watchState ${this._watchState}`);\n }\n\n // incoming state setup\n switch (this._watchState) {\n case 'WAITING_ACTIVE':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');\n break;\n case 'ACTIVE_LOCK':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');\n break;\n case 'ACTIVE_ERROR':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');\n break;\n case 'BACKGROUND':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');\n break;\n case 'BACKGROUND_ERROR':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error');\n break;\n case 'OFF':\n break;\n default:\n assert(false, `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('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.setAttribute('aria-pressed', 'true');\n\n this._geolocationWatchID = window.navigator.geolocation.watchPosition(\n this._onSuccess, this._onError, this.options.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: any);\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.setAttribute('aria-pressed', 'false');\n\n if (this.options.showUserLocation) {\n this._updateMarker(null);\n }\n }\n}\n\nexport default GeolocateControl;\n\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\n/**\n * Fired on each Geolocation API position update which returned as success.\n *\n * @event geolocate\n * @memberof GeolocateControl\n * @instance\n * @property {Position} 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 */\n\n/**\n * Fired on each Geolocation API position update which returned as an error.\n *\n * @event error\n * @memberof GeolocateControl\n * @instance\n * @property {PositionError} 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 */\n\n/**\n * Fired when the Geolocate Control 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 trackuserlocationstart\n * @memberof GeolocateControl\n * @instance\n *\n */\n\n/**\n * Fired when the Geolocate Control 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 trackuserlocationend\n * @memberof GeolocateControl\n * @instance\n *\n */\n","// @flow\n\nimport DOM from '../../util/dom';\nimport { extend, bindAll } from '../../util/util';\n\nimport type Map from '../map';\n\ntype Unit = 'imperial' | 'metric' | 'nautical';\n\ntype Options = {\n maxWidth?: number,\n unit?: Unit;\n};\n\nconst defaultOptions: Options = {\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 * @implements {IControl}\n * @param {Object} [options]\n * @param {number} [options.maxWidth='100'] The maximum length of the scale control in pixels.\n * @param {string} [options.unit='metric'] Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).\n * @example\n * var scale = new mapboxgl.ScaleControl({\n * maxWidth: 80,\n * unit: 'imperial'\n * });\n * map.addControl(scale);\n *\n * scale.setUnit('metric');\n */\nclass ScaleControl {\n _map: Map;\n _container: HTMLElement;\n options: Options;\n\n constructor(options: Options) {\n this.options = extend({}, defaultOptions, options);\n\n bindAll([\n '_onMove',\n 'setUnit'\n ], this);\n }\n\n getDefaultPosition() {\n return 'bottom-left';\n }\n\n _onMove() {\n updateScale(this._map, this._container, this.options);\n }\n\n onAdd(map: Map) {\n this._map = map;\n this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-scale', map.getContainer());\n\n this._map.on('move', this._onMove);\n this._onMove();\n\n return this._container;\n }\n\n onRemove() {\n DOM.remove(this._container);\n this._map.off('move', this._onMove);\n this._map = (undefined: any);\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\nexport default ScaleControl;\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 maxMeters = getDistance(map.unproject([0, y]), map.unproject([maxWidth, y]));\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, 'mi');\n } else {\n setScale(container, maxWidth, maxFeet, 'ft');\n }\n } else if (options && options.unit === 'nautical') {\n const maxNauticals = maxMeters / 1852;\n setScale(container, maxWidth, maxNauticals, 'nm');\n } else {\n setScale(container, maxWidth, maxMeters, 'm');\n }\n}\n\nfunction setScale(container, maxWidth, maxDistance, unit) {\n let distance = getRoundNum(maxDistance);\n const ratio = distance / maxDistance;\n\n if (unit === 'm' && distance >= 1000) {\n distance = distance / 1000;\n unit = 'km';\n }\n\n container.style.width = `${maxWidth * ratio}px`;\n container.innerHTML = distance + unit;\n}\n\nfunction getDistance(latlng1, latlng2) {\n // Uses spherical law of cosines approximation.\n const R = 6371000;\n\n const rad = Math.PI / 180,\n lat1 = latlng1.lat * rad,\n lat2 = latlng2.lat * rad,\n a = Math.sin(lat1) * Math.sin(lat2) +\n Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);\n\n const maxMeters = R * Math.acos(Math.min(a, 1));\n return maxMeters;\n\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","// @flow\n\nimport DOM from '../../util/dom';\n\nimport { bindAll, warnOnce } from '../../util/util';\nimport window from '../../util/window';\n\nimport type Map from '../map';\n\ntype Options = {\n container?: HTMLElement\n};\n\n/**\n * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode.\n *\n * @implements {IControl}\n * @param {Object} [options]\n * @param {HTMLElement} [options.container] `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 * @example\n * map.addControl(new mapboxgl.FullscreenControl({container: document.querySelector('body')}));\n * @see [View a fullscreen map](https://www.mapbox.com/mapbox-gl-js/example/fullscreen/)\n */\n\nclass FullscreenControl {\n _map: Map;\n _controlContainer: HTMLElement;\n _fullscreen: boolean;\n _fullscreenchange: string;\n _fullscreenButton: HTMLElement;\n _className: string;\n _container: HTMLElement;\n\n constructor(options: Options) {\n this._fullscreen = false;\n if (options && options.container) {\n if (options.container instanceof window.HTMLElement) {\n this._container = options.container;\n } else {\n warnOnce('Full screen control \\'container\\' must be a DOM element.');\n }\n }\n bindAll([\n '_onClickFullscreen',\n '_changeIcon'\n ], this);\n if ('onfullscreenchange' in window.document) {\n this._fullscreenchange = 'fullscreenchange';\n } else if ('onmozfullscreenchange' in window.document) {\n this._fullscreenchange = 'mozfullscreenchange';\n } else if ('onwebkitfullscreenchange' in window.document) {\n this._fullscreenchange = 'webkitfullscreenchange';\n } else if ('onmsfullscreenchange' in window.document) {\n this._fullscreenchange = 'MSFullscreenChange';\n }\n this._className = 'mapboxgl-ctrl';\n }\n\n onAdd(map: Map) {\n this._map = map;\n if (!this._container) this._container = this._map.getContainer();\n this._controlContainer = DOM.create('div', `${this._className} mapboxgl-ctrl-group`);\n if (this._checkFullscreenSupport()) {\n this._setupUI();\n } else {\n this._controlContainer.style.display = 'none';\n warnOnce('This device does not support fullscreen mode.');\n }\n return this._controlContainer;\n }\n\n onRemove() {\n DOM.remove(this._controlContainer);\n this._map = (null: any);\n window.document.removeEventListener(this._fullscreenchange, this._changeIcon);\n }\n\n _checkFullscreenSupport() {\n return !!(\n window.document.fullscreenEnabled ||\n (window.document: any).mozFullScreenEnabled ||\n (window.document: any).msFullscreenEnabled ||\n (window.document: any).webkitFullscreenEnabled\n );\n }\n\n _setupUI() {\n const button = this._fullscreenButton = DOM.create('button', (`${this._className}-icon ${this._className}-fullscreen`), this._controlContainer);\n button.type = 'button';\n this._updateTitle();\n this._fullscreenButton.addEventListener('click', this._onClickFullscreen);\n window.document.addEventListener(this._fullscreenchange, this._changeIcon);\n }\n\n _updateTitle() {\n const title = this._isFullscreen() ? \"Exit fullscreen\" : \"Enter fullscreen\";\n this._fullscreenButton.setAttribute(\"aria-label\", title);\n this._fullscreenButton.title = title;\n }\n\n _isFullscreen() {\n return this._fullscreen;\n }\n\n _changeIcon() {\n const fullscreenElement =\n window.document.fullscreenElement ||\n (window.document: any).mozFullScreenElement ||\n (window.document: any).webkitFullscreenElement ||\n (window.document: any).msFullscreenElement;\n\n if ((fullscreenElement === this._container) !== this._fullscreen) {\n this._fullscreen = !this._fullscreen;\n this._fullscreenButton.classList.toggle(`${this._className}-shrink`);\n this._fullscreenButton.classList.toggle(`${this._className}-fullscreen`);\n this._updateTitle();\n }\n }\n\n _onClickFullscreen() {\n if (this._isFullscreen()) {\n if (window.document.exitFullscreen) {\n (window.document: any).exitFullscreen();\n } else if (window.document.mozCancelFullScreen) {\n (window.document: any).mozCancelFullScreen();\n } else if (window.document.msExitFullscreen) {\n (window.document: any).msExitFullscreen();\n } else if (window.document.webkitCancelFullScreen) {\n (window.document: any).webkitCancelFullScreen();\n }\n } else if (this._container.requestFullscreen) {\n this._container.requestFullscreen();\n } else if ((this._container: any).mozRequestFullScreen) {\n (this._container: any).mozRequestFullScreen();\n } else if ((this._container: any).msRequestFullscreen) {\n (this._container: any).msRequestFullscreen();\n } else if ((this._container: any).webkitRequestFullscreen) {\n (this._container: any).webkitRequestFullscreen();\n }\n }\n}\n\nexport default FullscreenControl;\n","// @flow\n\nimport { extend, bindAll } from '../util/util';\nimport { Event, Evented } from '../util/evented';\nimport DOM from '../util/dom';\nimport LngLat from '../geo/lng_lat';\nimport Point from '@mapbox/point-geometry';\nimport window from '../util/window';\nimport smartWrap from '../util/smart_wrap';\nimport { type Anchor, anchorTranslate, applyAnchorClass } from './anchor';\n\nimport type Map from './map';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport type {PointLike} from '@mapbox/point-geometry';\n\nconst defaultOptions = {\n closeButton: true,\n closeOnClick: true,\n className: '',\n maxWidth: \"240px\"\n};\n\nexport type Offset = number | PointLike | {[Anchor]: PointLike};\n\nexport type PopupOptions = {\n closeButton?: boolean,\n closeOnClick?: boolean,\n anchor?: Anchor,\n offset?: Offset,\n className?: string,\n maxWidth?: string\n};\n\n/**\n * A popup component.\n *\n * @param {Object} [options]\n * @param {boolean} [options.closeButton=true] If `true`, a close button will appear in the\n * top right corner of the popup.\n * @param {boolean} [options.closeOnClick=true] If `true`, the popup will closed when the\n * map is clicked.\n * @param {string} [options.anchor] - 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 * @param {number|PointLike|Object} [options.offset] -\n * A pixel offset applied to the popup's location specified as:\n * - a single number specifying a distance from the popup's location\n * - a {@link PointLike} specifying a constant offset\n * - an object of {@link Point}s specifing an offset for each anchor position\n * Negative offsets indicate left and up.\n * @param {string} [options.className] Space-separated CSS class names to add to popup container\n * @param {string} [options.maxWidth='240px'] -\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 * @example\n * var markerHeight = 50, markerRadius = 10, linearOffset = 25;\n * var 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 * var popup = new mapboxgl.Popup({offset: popupOffsets, className: 'my-class'})\n * .setLngLat(e.lngLat)\n * .setHTML(\"

Hello World!

\")\n * .setMaxWidth(\"300px\")\n * .addTo(map);\n * @see [Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/)\n * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n * @see [Display a popup on click](https://www.mapbox.com/mapbox-gl-js/example/popup-on-click/)\n * @see [Attach a popup to a marker instance](https://www.mapbox.com/mapbox-gl-js/example/set-popup/)\n */\nexport default class Popup extends Evented {\n _map: Map;\n options: PopupOptions;\n _content: HTMLElement;\n _container: HTMLElement;\n _closeButton: HTMLElement;\n _tip: HTMLElement;\n _lngLat: LngLat;\n _trackPointer: boolean;\n _pos: ?Point;\n\n constructor(options: PopupOptions) {\n super();\n this.options = extend(Object.create(defaultOptions), options);\n bindAll(['_update', '_onClickClose', 'remove'], this);\n }\n\n /**\n * Adds the popup to a map.\n *\n * @param {Map} map The Mapbox GL JS map to add the popup to.\n * @returns {Popup} `this`\n */\n addTo(map: Map) {\n this._map = map;\n if (this.options.closeOnClick) {\n this._map.on('click', this._onClickClose);\n }\n\n this._map.on('remove', this.remove);\n this._update();\n\n if (this._trackPointer) {\n this._map.on('mousemove', (e) => { this._update(e.point); });\n this._map.on('mouseup', (e) => { this._update(e.point); });\n this._container.classList.add('mapboxgl-popup-track-pointer');\n this._map._canvasContainer.classList.add('mapboxgl-track-pointer');\n } else {\n this._map.on('move', this._update);\n }\n\n /**\n * Fired when the popup is opened manually or programatically.\n *\n * @event open\n * @memberof Popup\n * @instance\n * @type {Object}\n * @property {Popup} popup object that was opened\n */\n this.fire(new Event('open'));\n\n return this;\n }\n\n /**\n * @returns {boolean} `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 * var popup = new mapboxgl.Popup().addTo(map);\n * popup.remove();\n * @returns {Popup} `this`\n */\n remove() {\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('click', this._onClickClose);\n this._map.off('remove', this.remove);\n this._map.off('mousemove');\n delete this._map;\n }\n\n /**\n * Fired when the popup is closed manually or programatically.\n *\n * @event close\n * @memberof Popup\n * @instance\n * @type {Object}\n * @property {Popup} popup object that was closed\n */\n this.fire(new Event('close'));\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 {LngLat} The geographical location of the popup's anchor.\n */\n getLngLat() {\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 * @returns {Popup} `this`\n */\n setLngLat(lnglat: LngLatLike) {\n this._lngLat = LngLat.convert(lnglat);\n this._pos = 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');\n this._container.classList.remove('mapboxgl-popup-track-pointer');\n this._map._canvasContainer.classList.remove('mapboxgl-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 (will be hidden on touchscreens). Replaces the setLngLat behavior.\n * For most use cases, `closeOnClick` and `closeButton` should also be set to `false` here.\n * @returns {Popup} `this`\n */\n trackPointer() {\n this._trackPointer = true;\n this._pos = null;\n\n if (this._map) {\n this._map.off('move', this._update);\n this._map.on('mousemove', (e) => { this._update(e.point); });\n this._map.on('drag', (e) => { this._update(e.point); });\n this._container.classList.add('mapboxgl-popup-track-pointer');\n this._map._canvasContainer.classList.add('mapboxgl-track-pointer');\n }\n\n return this;\n\n }\n\n /**\n * Returns the `Popup`'s HTML element.\n * @returns {HTMLElement} element\n */\n getElement() {\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 * @returns {Popup} `this`\n * @example\n * var popup = new mapboxgl.Popup()\n * .setLngLat(e.lngLat)\n * .setText('Hello, world!')\n * .addTo(map);\n */\n setText(text: string) {\n return this.setDOMContent(window.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 * @returns {Popup} `this`\n */\n setHTML(html: string) {\n const frag = window.document.createDocumentFragment();\n const temp = window.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 {string} The maximum width of the popup.\n */\n getMaxWidth() {\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 * @returns {Popup} `this`\n */\n setMaxWidth(maxWidth: string) {\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 * @returns {Popup} `this`\n * @example\n * // create an element with the popup content\n * var div = window.document.createElement('div');\n * div.innerHTML = 'Hello, world!';\n * var popup = new mapboxgl.Popup()\n * .setLngLat(e.lngLat)\n * .setDOMContent(div)\n * .addTo(map);\n */\n setDOMContent(htmlNode: Node) {\n this._createContent();\n this._content.appendChild(htmlNode);\n this._update();\n return this;\n }\n\n _createContent() {\n if (this._content) {\n DOM.remove(this._content);\n }\n\n this._content = DOM.create('div', 'mapboxgl-popup-content', this._container);\n if (this.options.closeButton) {\n this._closeButton = DOM.create('button', 'mapboxgl-popup-close-button', this._content);\n this._closeButton.type = 'button';\n this._closeButton.setAttribute('aria-label', 'Close popup');\n this._closeButton.innerHTML = '×';\n this._closeButton.addEventListener('click', this._onClickClose);\n }\n\n }\n\n _update(cursor: PointLike) {\n\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', 'mapboxgl-popup', this._map.getContainer());\n this._tip = DOM.create('div', 'mapboxgl-popup-tip', this._container);\n this._container.appendChild(this._content);\n if (this.options.className) {\n this.options.className.split(' ').forEach(name =>\n this._container.classList.add(name));\n }\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._pos, this._map.transform);\n }\n\n if (this._trackPointer && !cursor) return;\n\n const pos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat);\n\n let anchor: ?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('-'): any);\n }\n }\n\n const offsetedPos = pos.add(offset[anchor]).round();\n DOM.setTransform(this._container, `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`);\n applyAnchorClass(this._container, anchor, 'popup');\n }\n\n _onClickClose() {\n this.remove();\n }\n}\n\nfunction normalizeOffset(offset: ?Offset) {\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.sqrt(0.5 * Math.pow(offset, 2)));\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","// @flow\n\nimport assert from 'assert';\nimport supported from '@mapbox/mapbox-gl-supported';\n\nimport { version } from '../package.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 ScaleControl from './ui/control/scale_control';\nimport FullscreenControl from './ui/control/fullscreen_control';\nimport Popup from './ui/popup';\nimport Marker from './ui/marker';\nimport Style from './style/style';\nimport LngLat from './geo/lng_lat';\nimport LngLatBounds 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 {setRTLTextPlugin} from './source/rtl_text_plugin';\nimport WorkerPool from './util/worker_pool';\nimport {clearTileCache} from './util/tile_request_cache';\n\nconst exported = {\n version,\n supported,\n setRTLTextPlugin,\n Map,\n NavigationControl,\n GeolocateControl,\n AttributionControl,\n ScaleControl,\n FullscreenControl,\n Popup,\n Marker,\n Style,\n LngLat,\n LngLatBounds,\n Point,\n MercatorCoordinate,\n Evented,\n config,\n\n /**\n * Gets and sets the map's [access token](https://www.mapbox.com/help/define-access-token/).\n *\n * @var {string} accessToken\n * @example\n * mapboxgl.accessToken = myAccessToken;\n * @see [Display a map](https://www.mapbox.com/mapbox-gl-js/examples/)\n */\n get accessToken(): ?string {\n return config.ACCESS_TOKEN;\n },\n\n set accessToken(token: string) {\n config.ACCESS_TOKEN = token;\n },\n\n /**\n * Gets and sets the map's default API URL for requesting tiles, styles, sprites, and glyphs\n *\n * @var {string} baseApiUrl\n * @example\n * mapboxgl.baseApiUrl = 'https://api.mapbox.com';\n */\n get baseApiUrl(): ?string {\n return config.API_URL;\n },\n\n set baseApiUrl(url: string) {\n config.API_URL = url;\n },\n\n /**\n * Gets and sets the number of web workers instantiated on a page with GL JS maps.\n * By default, it is set to half the number of CPU cores (capped at 6).\n * Make sure to set this property before creating any map instances for it to have effect.\n *\n * @var {string} workerCount\n * @example\n * mapboxgl.workerCount = 2;\n */\n get workerCount(): number {\n return WorkerPool.workerCount;\n },\n\n set workerCount(count: number) {\n WorkerPool.workerCount = count;\n },\n\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 * @var {string} maxParallelImageRequests\n * @example\n * mapboxgl.maxParallelImageRequests = 10;\n */\n get maxParallelImageRequests(): number {\n return config.MAX_PARALLEL_IMAGE_REQUESTS;\n },\n\n set maxParallelImageRequests(numRequests: number) {\n config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests;\n },\n\n /**\n * Clears browser storage used by this library. Using this method flushes the Mapbox tile\n * cache that is managed by this library. Tiles may still be cached by the browser\n * in some cases.\n *\n * This API is supported on browsers where the [`Cache` API](https://developer.mozilla.org/en-US/docs/Web/API/Cache)\n * is supported and enabled. This includes all major browsers when pages are served over\n * `https://`, except Internet Explorer and Edge Mobile.\n *\n * When called in unsupported browsers or environments (private or incognito mode), the\n * callback will be called with an error argument.\n *\n * @function clearStorage\n * @param {Function} callback Called with an error argument if there is an error.\n */\n clearStorage(callback?: (err: ?Error) => void) {\n clearTileCache(callback);\n },\n\n workerUrl: ''\n};\n\n/**\n * The version of Mapbox GL JS in use as specified in `package.json`,\n * `CHANGELOG.md`, and the GitHub release.\n *\n * @var {string} version\n */\n\n/**\n * Test whether the browser [supports Mapbox GL JS](https://www.mapbox.com/help/mapbox-browser-support/#mapbox-gl-js).\n *\n * @function supported\n * @param {Object} [options]\n * @param {boolean} [options.failIfMajorPerformanceCaveat=false] If `true`,\n * the function will return `false` if the performance of Mapbox GL JS would\n * be dramatically worse than expected (e.g. a software WebGL renderer would be used).\n * @return {boolean}\n * @example\n * mapboxgl.supported() // = true\n * @see [Check for browser support](https://www.mapbox.com/mapbox-gl-js/example/check-for-support/)\n */\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. Mapbox Studio loads this plugin by default.\n *\n * @function setRTLTextPlugin\n * @param {string} pluginURL URL pointing to the Mapbox RTL text plugin source.\n * @param {Function} callback Called with an error argument if there is an error.\n * @example\n * mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.0/mapbox-gl-rtl-text.js');\n * @see [Add support for right-to-left scripts](https://www.mapbox.com/mapbox-gl-js/example/mapbox-gl-rtl-text/)\n */\n\nexport default exported;\n\n// canary assert: used to confirm that asserts have been removed from production build\nassert(true, 'canary assert');\n"],"names":["isSupported","options","window","document","Array","prototype","every","filter","forEach","indexOf","lastIndexOf","map","some","reduce","reduceRight","isArray","Function","bind","Object","keys","create","getPrototypeOf","getOwnPropertyNames","isSealed","isFrozen","isExtensible","getOwnPropertyDescriptor","defineProperty","defineProperties","seal","freeze","preventExtensions","JSON","supported","worker","blob","Blob","type","workerURL","URL","createObjectURL","Worker","e","terminate","revokeObjectURL","isWorkerSupported","ArrayBuffer","isView","failIfMajorPerformanceCaveat","undefined","isWebGLSupportedCache","canvas","createElement","attributes","webGLContextAttributes","probablySupportsContext","supportsContext","getContext","isWebGLSupported","isWebGLSupportedCached","module","exports","mapboxgl","antialias","alpha","stencil","depth","UnitBezier","p1x","p1y","p2x","p2y","this","cx","bx","ax","cy","by","ay","sampleCurveX","t","sampleCurveY","sampleCurveDerivativeX","solveCurveX","x","epsilon","t0","t1","t2","x2","i","Math","abs","d2","solve","Point","y","deepEqual","a","b","length","let","key","bezier","const","clone","add","p","_add","sub","_sub","multByPoint","_multByPoint","divByPoint","_divByPoint","mult","k","_mult","div","_div","rotate","_rotate","rotateAround","_rotateAround","matMult","m","_matMult","unit","_unit","perp","_perp","round","_round","mag","sqrt","equals","other","dist","distSqr","dx","dy","angle","atan2","angleTo","angleWith","angleWithSep","cos","sin","convert","ease","clamp","n","min","max","wrap","d","w","asyncAll","array","fn","callback","remaining","results","error","item","err","result","extend","dest","sources","src","pick","properties","id","uniqueId","uuid","random","toString","replace","validateUuid","str","test","bindAll","fns","context","endsWith","string","suffix","mapObject","input","iterator","output","call","filterObject","warnOnceHistory","warnOnce","message","console","warn","isCounterClockwise","c","calculateSignedArea","ring","sum","len","j","p1","p2","parseCacheControl","cacheControl","header","$0","$1","$2","$3","value","toLowerCase","maxAge","parseInt","isNaN","storageAvailable","storage","setItem","removeItem","linkEl","reducedMotionQuery","now","performance","Date","raf","requestAnimationFrame","mozRequestAnimationFrame","webkitRequestAnimationFrame","msRequestAnimationFrame","cancel","cancelAnimationFrame","mozCancelAnimationFrame","webkitCancelAnimationFrame","msCancelAnimationFrame","exported","frame","getImageData","img","Error","width","height","drawImage","resolveURL","path","href","hardwareConcurrency","navigator","devicePixelRatio","prefersReducedMotion","matchMedia","matches","DOM","tagName","className","container","el","appendChild","namespaceURI","createElementNS","docStyle","documentElement","style","testProp","props","userSelect","selectProp","disableDrag","enableDrag","transformProp","setTransform","passiveSupported","get","addEventListener","removeEventListener","target","capture","suppressClick","preventDefault","stopPropagation","setTimeout","mousePos","rect","getBoundingClientRect","TouchEvent","touches","clientX","left","clientLeft","clientY","top","clientTop","touchPos","points","changedTouches","push","mouseButton","InstallTrigger","button","ctrlKey","platform","toUpperCase","remove","node","parentNode","removeChild","glForTesting","webpImgTest","config","API_URL","EVENTS_URL","FEEDBACK_URL","REQUIRE_ACCESS_TOKEN","ACCESS_TOKEN","MAX_PARALLEL_IMAGE_REQUESTS","gl","webpCheckComplete","webpImgTestOnloadComplete","testWebpTextureUpload","texture","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","isContextLost","deleteTexture","onload","onerror","SKU_ID","RequestManager","transformRequestFn","customAccessToken","_transformRequestFn","_customAccessToken","_createSkuToken","isMapboxURL","url","skuToken","sessionRandomizer","floor","join","createSkuToken","_skuToken","token","_skuTokenExpiresAt","tokenExpiresAt","_isSkuTokenExpired","transformRequest","normalizeStyleURL","accessToken","urlObject","parseUrl","_makeAPIURL","normalizeGlyphsURL","normalizeSourceURL","authority","params","normalizeSpriteURL","format","extension","formatUrl","normalizeTileURL","tileURL","sourceURL","tileSize","browser","webpSupported","canonicalizeTileURL","match","canonicalizeTileset","tileJSON","tiles","canonical","canonicalUrl","help","apiUrlObject","protocol","mapboxHTTPURLRe","isMapboxHTTPURL","urlRe","parts","split","obj","parseAccessToken","parse","decodeURIComponent","atob","charCodeAt","slice","TelemetryEvent","anonId","eventData","queue","pendingRequest","getStorageKey","domain","tokenData","u","btoa","encodeURIComponent","String","fromCharCode","Number","telemEventKey","fetchEventData","isLocalStorageAvailable","storageKey","uuidKey","data","localStorage","getItem","saveEventData","stringify","processRequests","_","postEvent","timestamp","additionalPayload","eventsUrlObject","payload","event","created","toISOString","sdkIdentifier","sdkVersion","skuId","userId","finalPayload","request","headers","Content-Type","body","postData","queueRequest","responseConstructorSupportsReadableStream","MapLoadEvent","super","success","postMapLoadEvent","tileUrls","mapId","shift","turnstileEvent_","postTurnstileEvent","lastSuccess","tokenU","dueForEvent","nextUpdate","lastUpdate","nextDate","daysElapsed","getDate","enabled.telemetry","mapLoadEvent_","CACHE_NAME","cacheLimit","cacheCheckThreshold","MIN_TIME_UNTIL_EXPIRY","cachePut","response","requestTime","caches","status","statusText","Headers","v","set","toUTCString","getTime","Response","ReadableStream","then","prepareBody","clonedResponse","open","cache","put","stripQueryParameters","catch","start","cacheGet","strippedURL","fresh","expires","isFresh","delete","globalEntryCounter","Infinity","cacheEntryPossiblyAdded","dispatcher","getActor","send","ResourceType","Unknown","Style","Source","Tile","Glyphs","SpriteImage","SpriteJSON","Image","AJAXError","name","constructor","isWorker","WorkerGlobalScope","self","getReferrer","referrer","location","parent","makeFetchRequest","requestParameters","controller","AbortController","Request","method","credentials","signal","complete","aborted","cacheIgnoringSearch","validateOrFetch","cachedResponse","responseIsFresh","finishRequest","fetch","ok","cacheableResponse","code","arrayBuffer","json","text","abort","makeRequest","hasOwnProperty","actor","xhr","XMLHttpRequest","responseType","setRequestHeader","withCredentials","getResponseHeader","makeXMLHttpRequest","getJSON","getArrayBuffer","imageQueue","numImageRequests","getImage","queued","cancelled","advanced","advanceImageRequestQueue","webkitURL","Uint8Array","byteLength","_addEventListener","listener","listenerList","_removeEventListener","index","splice","Event","ErrorEvent","Evented","on","_listeners","off","_oneTimeListeners","once","fire","listens","listener$1","_eventedParent","_eventedParentData","setEventedParent","ValidationError","identifier","__line__","line","validateConstants","constants","inputs","isPrimitive","Boolean","unbundle","valueOf","deepUnbundle","unbundledValue","ParsingError","Scope","bindings","ref","expression","concat","has","NullType","kind","NumberType","StringType","BooleanType","ColorType","ObjectType","ValueType","CollatorType","FormattedType","itemType","N","valueMemberTypes","checkSubtype","expected","kCSSColorTable","transparent","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","clamp_css_byte","clamp_css_float","f","parse_css_int","parseFloat","parse_css_float","css_hue_to_rgb","m1","m2","h","css_str","iv","substr","op","ep","fname","pop","s","l","Color","r","g","rgba","parseCSSColor","toArray","Collator","caseSensitive","diacriticSensitive","locale","sensitivity","collator","Intl","usage","compare","lhs","rhs","resolvedLocale","resolvedOptions","FormattedSection","scale","fontStack","textColor","Formatted","sections","validateRGBA","typeOf","fromString","unformatted","section","serialize","serialized","Literal","args","isValue","mixed","expectedType","evaluate","eachChild","possibleOutputs","RuntimeError","toJSON","types","number","boolean","object","Assertion","parsed","ctx","arg","FormatExpression","font","to-boolean","to-color","to-number","to-string","Coercion","parseColor","num","valueToString","child","geometryTypes","EvaluationContext","globals","feature","featureState","formattedSection","_parseColorCache","geometryType","cached","CompoundExpression","_evaluate","definition","definitions","availableOverloads","overloads","signature","signatureContext","ParsingContext","registry","scope","parsedArgs","argParseFailed","errors","ref$1","signatures","actualTypes","register","CollatorExpression","isFeatureConstant","isStateConstant","isGlobalPropertyConstant","Var","boundExpression","part","findStopLessThanOrEqualTo","stops","currentValue","nextValue","lastIndex","lowerIndex","upperIndex","currentIndex","expr","_parse","annotate","typeAnnotation","Expr","actual","isConstant","isTypeAnnotation","childrenConstant","ec","Step","labels","outputs","label","outputType","labelKey","valueKey","stopCount","from","to","Xn","Yn","Zn","t3","deg2rad","PI","rad2deg","xyz2lab","pow","lab2xyz","xyz2rgb","rgb2xyz","rgbToLab","rgbColor","labToRgb","labColor","z","interpolateHue","lab","forward","reverse","interpolate","interpolateNumber","hcl","hclColor","Interpolate","operator","interpolation","exponentialInterpolation","base","lowerValue","upperValue","difference","progress","interpolationFactor","lower","upper","controlPoints","rest","outputLower","outputUpper","Coalesce","needsAnnotation","Let","At","Match","inputType","cases","otherwise","labelContext","MAX_SAFE_INTEGER","out","groupedByOutput","outputLookup","sort","outputIndex","coerceLabel","Case","branches","isComparableType","eqCollate","makeComparison","compareBasic","compareWithCollator","isOrderComparison","hasUntypedArgument","Comparison","lt","rt","Equals","NotEquals","LessThan","GreaterThan","LessThanOrEqual","GreaterThanOrEqual","NumberFormat","currency","minFractionDigits","maxFractionDigits","minimumFractionDigits","maximumFractionDigits","Length","expressions","==","!=",">","<",">=","<=","at","case","coalesce","interpolate-hcl","interpolate-lab","literal","number-format","step","var","varargs","supportsPropertyExpression","spec","supportsZoomExpression","parameters","supportsInterpolation","interpolated","getType","val","isFunction","identityFunction","evaluateCategoricalFunction","propertySpec","hashedStops","keyType","default","evaluateIntervalFunction","stop","evaluateExponentialFunction","interp","colorSpace","colorspace","colorSpaces","evaluatedLower","apply","evaluatedUpper","evaluateIdentityFunction","values","typeof","typeToString","to-rgba","rgb","feature-state","geometry-type","zoom","heatmap-density","heatmapDensity","line-progress","lineProgress","accumulated","+","*","-","/","%","ln2","LN2","pi","E","^","log10","log","LN10","ln","log2","asin","acos","atan","ceil","filter-==","filter-id-==","filter-type-==","filter-<","filter-id-<","filter->","filter-id->","filter-<=","filter-id-<=","filter->=","filter-id->=","filter-has","filter-has-id","filter-type-in","filter-id-in","filter-in-small","filter-in-large","binarySearch","all","any","!","is-supported-script","isSupportedScript","upcase","downcase","resolved-locale","StyleExpression","_warningHistory","_evaluator","_defaultValue","getDefaultValue","_enumValues","isExpression","createExpression","parser","color","enum","formatted","getExpectedType","evaluateWithoutErrorHandling","ZoomConstantExpression","_styleExpression","isStateDependent","ZoomDependentExpression","zoomStops","interpolationType","createPropertyExpression","isZoomConstant","zoomCurve","findZoomCurve","childResult","StylePropertyFunction","specification","_parameters","_specification","createFunction","innerFun","categoricalKeyType","isColor","zoomAndFeatureDependent","featureDependent","property","zoomDependent","featureFunctions","featureFunctionStops","validateObject","elementSpecs","valueSpec","elementValidators","objectElementValidators","styleSpec","objectKey","elementSpecKey","elementSpec","validateElement","validateSpec","required","validateArray","arraySpec","validateArrayElement","arrayElementValidator","validate","arrayElementSpec","$version","function","arrayIndex","validateNumber","minimum","maximum","validateFunction","stopKeyType","previousStopDomainValue","previousStopDomainZoom","functionValueSpec","functionType","stopDomainValues","isZoomFunction","isPropertyFunction","isZoomAndPropertyFunction","validateFunctionStop","validateStopDomainValue","reportValue","isFinite","validateExpression","expressionContext","expressionObj","propertyKey","propertyType","validateEnum","isExpressionFilter","deserialize","filterSpec","transition","property-type","createFilter","convertFilter","compiled","globalProperties","filters","convertComparisonOp","convertNegation","convertInOp","convertHasOp","validateFilter","validateNonExpressionFilter","filter_operator","geometry_type","validateProperty","layerSpec","layerType","transitionMatch","tokenMatch","tokens","exec","glyphs","validatePaintProperty","validateLayoutProperty","validateLayer","layer","layerId","otherLayer","layers","source","sourceType","paint","lineMetrics","layout","validateSource","source_geojson","cluster","prop","clusterProperties","reduceExpr","mapExpr","source_video","source_image","validateLight","light","lightSpec","rootType","validateString","VALIDATORS","validateStyleMin","latestStyleSpec","$root","validateGlyphsURL","sortErrors","wrapCleanErrors","inner","paintProperty","layoutProperty","validateStyle","emitValidationErrors","emitter","hasErrors","GridIndex","NUM_PARAMS","extent","padding","cells","Int32Array","end","subarray","keysOffset","bboxesOffset","bboxes","insert","_insertReadonly","uid","x1","y1","y2","_forEachCell","_insertCell","cellIndex","query","intersectionTest","_queryCell","seenUids","cell","offset","arg1","arg2","cx1","_convertToCellCoord","cy1","cx2","cy2","_convertFromCellCoord","toArrayBuffer","metadataLength","totalCellLength","buffer","klass","writeable","omit","shallow","Grid","grid","transferables","_classRegistryKey","RegExp","view","ImageData","$name","ZoomHistory","first","update","floorZ","lastIntegerZoom","lastIntegerZoomTime","lastZoom","lastFloorZoom","unicodeBlockLookup","Latin-1 Supplement","char","Arabic","Arabic Supplement","Arabic Extended-A","Hangul Jamo","Unified Canadian Aboriginal Syllabics","Khmer","Unified Canadian Aboriginal Syllabics Extended","General Punctuation","Letterlike Symbols","Number Forms","Miscellaneous Technical","Control Pictures","Optical Character Recognition","Enclosed Alphanumerics","Geometric Shapes","Miscellaneous Symbols","Miscellaneous Symbols and Arrows","CJK Radicals Supplement","Kangxi Radicals","Ideographic Description Characters","CJK Symbols and Punctuation","Hiragana","Katakana","Bopomofo","Hangul Compatibility Jamo","Kanbun","Bopomofo Extended","CJK Strokes","Katakana Phonetic Extensions","Enclosed CJK Letters and Months","CJK Compatibility","CJK Unified Ideographs Extension A","Yijing Hexagram Symbols","CJK Unified Ideographs","Yi Syllables","Yi Radicals","Hangul Jamo Extended-A","Hangul Syllables","Hangul Jamo Extended-B","Private Use Area","CJK Compatibility Ideographs","Arabic Presentation Forms-A","Vertical Forms","CJK Compatibility Forms","Small Form Variants","Arabic Presentation Forms-B","Halfwidth and Fullwidth Forms","allowsVerticalWritingMode","chars","charHasUprightVerticalOrientation","isChar","charInSupportedScript","canRenderRTL","_completionCallback","pluginRequested","pluginURL","foregroundLoadComplete","evented","plugin","applyArabicShaping","processBidirectionalText","processStyledBidirectionalText","isLoaded","EvaluationParameters","fadeDuration","zoomHistory","isStringInSupportedScript","rtlTextPlugin","crossFadingFactor","getCrossfadeParameters","fraction","fromScale","toScale","PropertyValue","constant","normalizePropertyExpression","isDataDriven","possiblyEvaluate","TransitionablePropertyValue","transitioned","prior","TransitioningPropertyValue","untransitioned","Transitionable","_properties","_values","defaultTransitionablePropertyValues","getValue","setValue","getTransition","setTransition","Transitioning","begin","delay","duration","finalValue","easeCubicInOut","defaultTransitioningPropertyValues","PossiblyEvaluated","hasTransition","Layout","defaultPropertyValues","PossiblyEvaluatedPropertyValue","constantOr","defaultPossiblyEvaluatedValues","DataConstantProperty","DataDrivenProperty","overrides","CrossFadedDataDrivenProperty","constantValue","_calculate","cameraVal","mid","CrossFadedProperty","ColorRampProperty","Properties","overridableProperties","overridable","defaultPropertyValue","defaultTransitionablePropertyValue","StyleLayer","_featureFilter","metadata","minzoom","maxzoom","sourceLayer","_unevaluatedLayout","_transitionablePaint","setPaintProperty","setLayoutProperty","_transitioningPaint","_crossfadeParameters","getLayoutProperty","visibility","_validate","getPaintProperty","transitionable","isCrossFadedProperty","wasDataDriven","oldValue","_handleSpecialPaintPropertyUpdate","newValue","_handleOverridablePaintPropertyUpdate","isHidden","updateTransitions","recalculate","source-layer","sprite","is3D","isTileClipped","hasOffscreenPass","resize","viewTypes","Int8","Int8Array","Uint8","Int16","Int16Array","Uint16","Uint16Array","Int32","Uint32","Uint32Array","Float32","Float32Array","Struct","structArray","_structArray","_pos1","size","_pos2","_pos4","_pos8","StructArray","isTransferred","capacity","createLayout","members","alignment","maxSize","member","typeSize","BYTES_PER_ELEMENT","memberOffset","align","components","_trim","bytesPerElement","_refreshViews","clear","reserve","oldUint8Array","uint8","StructArrayLayout2i4","int16","emplaceBack","v0","v1","emplace","o2","StructArrayLayout4i8","v2","v3","StructArrayLayout2i4i12","v4","v5","StructArrayLayout2i4ub8","o1","StructArrayLayout8ui16","uint16","v6","v7","StructArrayLayout4i4ui16","StructArrayLayout3f12","float32","o4","StructArrayLayout1ul4","uint32","StructArrayLayout6i1ul2ui2i24","v8","v9","v10","StructArrayLayout2i2i2i12","StructArrayLayout2ub2f12","StructArrayLayout2i2ui3ul3ui2f3ub1ul44","v11","v12","v13","v14","v15","StructArrayLayout6i11ui1ul2f48","v16","v17","v18","v19","StructArrayLayout1f4","StructArrayLayout3i6","StructArrayLayout1ul2ui8","StructArrayLayout3ui6","StructArrayLayout2ui4","StructArrayLayout1ui2","StructArrayLayout2f8","StructArrayLayout4f16","CollisionBoxStruct","prototypeAccessors","anchorPointX","anchorPointY","featureIndex","sourceLayerIndex","bucketIndex","radius","signedDistanceFromAnchor","anchorPoint","CollisionBoxArray","PlacedSymbolStruct","prototypeAccessors$1","anchorX","anchorY","glyphStartIndex","numGlyphs","vertexStartIndex","lineStartIndex","lineLength","segment","lowerSize","upperSize","lineOffsetX","lineOffsetY","writingMode","placedOrientation","hidden","crossTileID","PlacedSymbolArray","SymbolInstanceStruct","prototypeAccessors$2","rightJustifiedTextSymbolIndex","centerJustifiedTextSymbolIndex","leftJustifiedTextSymbolIndex","verticalPlacedTextSymbolIndex","textBoxStartIndex","textBoxEndIndex","verticalTextBoxStartIndex","verticalTextBoxEndIndex","iconBoxStartIndex","iconBoxEndIndex","numHorizontalGlyphVertices","numVerticalGlyphVertices","numIconVertices","textBoxScale","radialTextOffset","SymbolInstanceArray","GlyphOffsetStruct","prototypeAccessors$3","offsetX","GlyphOffsetArray","getoffsetX","SymbolLineVertexStruct","prototypeAccessors$4","tileUnitDistanceFromAnchor","SymbolLineVertexArray","getx","gety","gettileUnitDistanceFromAnchor","FeatureIndexStruct","prototypeAccessors$5","FeatureIndexArray","SegmentVector","segments","packUint8ToFloat","prepareSegment","numVertices","layoutVertexArray","indexArray","sortKey","MAX_VERTEX_ARRAY_LENGTH","vertexLength","vertexOffset","primitiveOffset","primitiveLength","destroy","vaos","simpleSegment","FeaturePositionMap","ids","positions","indexed","swap","arr","tmp","getPositions","Float64Array","right","pivot","Uniform","Uniform1i","current","uniform1i","Uniform1f","uniform1f","Uniform2f","uniform2f","Uniform3f","uniform3f","Uniform4f","uniform4f","UniformColor","emptyMat4","UniformMatrix4f","uniformMatrix4fv","packColor","ConstantBinder","names","uniformNames","maxValue","defines","setConstantPatternPositions","populatePaintArray","updatePaintArray","upload","setUniforms","uniform","getBinding","binder","CrossFadedConstantBinder","patternPositions","patternTo","patternFrom","posTo","posFrom","tlbr","uniformName","pos","SourceExpressionBinder","PaintVertexArray","paintVertexAttributes","paintVertexArray","newLength","imagePositions","paintArray","paintVertexBuffer","updateData","createVertexBuffer","CompositeExpressionBinder","useIntegerZoom","minColor","maxColor","currentZoom","CrossFadedCompositeBinder","zoomInPaintVertexArray","zoomOutPaintVertexArray","zoomInArray","zoomOutArray","patterns","imageMin","imageMid","imageMax","tl","br","zoomInPaintVertexBuffer","zoomOutPaintVertexBuffer","ProgramConfiguration","binders","cacheKey","_buffers","_featureMap","_bufferOffset","createDynamic","filterProperties","paintAttributeNames","StructArrayLayout","layoutType","populatePaintArrays","updatePaintArrays","featureStates","vtLayer","dirty","getPaintVertexBuffers","getUniforms","locations","uniforms","binding","binderUniforms","updatePatternPaintBuffers","crossfade","buffers","patternVertexBuffer","ProgramConfigurationSet","layoutAttributes","programConfigurations","needsUpload","text-opacity","icon-opacity","text-color","icon-color","text-halo-color","icon-halo-color","text-halo-blur","icon-halo-blur","text-halo-width","icon-halo-width","line-gap-width","line-pattern","fill-pattern","fill-extrusion-pattern","binderType","defaultLayouts","composite","layoutException","PatternLayoutArray","getLayoutException","bits","bounds","loadGeometry","EXTENT","geometry","point","addCircleVertex","extrudeX","extrudeY","CircleBucket","overscaling","layerIds","hasPattern","CircleLayoutArray","TriangleIndexArray","stateDependentLayerIds","polygonIntersectsPolygon","polygonA","polygonB","polygonContainsPoint","lineIntersectsLine","polygonIntersectsBufferedPoint","polygon","pointIntersectsBufferedLine","polygonIntersectsMultiPolygon","multiPolygon","multiPolygonContainsPoint","lineIntersectsBufferedLine","lineA","lineB","a0","a1","lineSegmentIntersectsLineSegment","b0","b1","radiusSquared","distToSegmentSquared","l2","rings","edgeIntersectsBox","e1","e2","corners","dir","getMaximumPaintValue","bucket","translateDistance","translate","queryGeometry","translateAnchor","bearing","pixelsToTileUnits","pt","translated","populate","features","styleLayer","bucketFeatures","circleSortKey","bucketFeature","addFeature","states","stateDependentLayers","isEmpty","uploadPending","uploaded","layoutVertexBuffer","indexBuffer","createIndexBuffer","circle-sort-key","circle-radius","circle-color","circle-blur","circle-opacity","circle-translate","circle-translate-anchor","circle-pitch-scale","circle-pitch-alignment","circle-stroke-width","circle-stroke-color","circle-stroke-opacity","ARRAY_TYPE","glMatrix","identity","multiply","a00","a01","a02","a03","a10","a11","a12","a13","a20","a21","a22","a23","a30","a31","a32","a33","b2","b3","rotateZ","rad","ortho","bottom","near","far","lr","bt","nf","hypot","arguments","vec","transformMat4","CircleStyleLayer","createBucket","queryRadius","circleBucket","queryIntersectsFeature","transform","pixelPosMatrix","translatedPolygon","alignWithMap","transformedPolygon","projectPoint","projectQueryGeometry","transformedSize","transformedPoint","adjustedSize","projectedCenter","vec4","cameraToCenterDistance","HeatmapBucket","createImage","image","channels","Uint8ClampedArray","RangeError","resizeImage","newImage","copyImage","srcImg","dstImg","srcPt","dstPt","srcData","dstData","srcOffset","dstOffset","AlphaImage","copy","RGBAImage","heatmap-radius","heatmap-weight","heatmap-intensity","heatmap-color","heatmap-opacity","renderColorRamp","colorRampEvaluationParameter","colorRampData","evaluationGlobals","pxColor","HeatmapStyleLayer","_updateColorRamp","colorRamp","colorRampTexture","heatmapFbo","hillshade-illumination-direction","hillshade-illumination-anchor","hillshade-exaggeration","hillshade-shadow-color","hillshade-highlight-color","hillshade-accent-color","HillshadeStyleLayer","earcut","holeIndices","dim","minX","minY","maxX","maxY","invSize","hasHoles","outerLen","outerNode","linkedList","triangles","next","prev","list","steiner","getLeftmost","compareX","eliminateHole","filterPoints","eliminateHoles","earcutLinked","clockwise","last","signedArea","insertNode","removeNode","again","area","ear","pass","zOrder","prevZ","nextZ","q","tail","numMerges","pSize","qSize","inSize","sortLinked","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","minTX","minTY","maxTX","maxTY","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","hole","hx","hy","qx","mx","my","tanMin","sectorContainsSector","findHoleBridge","leftmost","px","py","intersectsPolygon","inside","middleInside","q1","q2","sign","o3","onSegment","a2","Node","an","bp","quickselect","quickselectStep","exp","sd","newLeft","newRight","defaultCompare","classifyRings","maxRings","ccw","polygons","compareAreas","patternDependencies","patternProperty","constantPattern","addPatternDependencies","patternFeature","patternPropertyValue","deviation","polygonArea","trianglesArea","flatten","vertices","holes","dimensions","holeIndex","FillBucket","patternFeatures","FillLayoutArray","indexArray2","LineIndexArray","segments2","fillSortKey","addFeatures","indexBuffer2","triangleSegment","triangleIndex","flattened","lineSegment","lineIndex","indices","fill-sort-key","fill-antialias","fill-opacity","fill-color","fill-outline-color","fill-translate","fill-translate-anchor","FillStyleLayer","outlineColor","VectorTileFeature","pbf","_pbf","_geometry","_keys","readFields","readFeature","tag","readVarint","readTag","cmd","lines","cmdLen","readSVarint","bbox","toGeoJSON","x0","y0","coords","project","coordinates","VectorTileLayer","version","_features","readLayer","readString","readFloat","readDouble","readVarint64","readBoolean","readValueMessage","readTile","require","vectorTileFeatureTypes","mvt","FACTOR","addVertex","vertexArray","nx","ny","nz","FillExtrusionBucket","FillExtrusionLayoutArray","isBoundaryEdge","isEntirelyOutside","edgeDistance","bottomRight","fill-extrusion-opacity","fill-extrusion-color","fill-extrusion-translate","fill-extrusion-translate-anchor","fill-extrusion-height","fill-extrusion-base","fill-extrusion-vertical-gradient","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","topB","baseA","baseB","face","checkIntersection","dot","projectedFace","ab","ac","ap","dotABAB","dotABAC","dotACAC","dotAPAB","dotAPAC","denom","COS_HALF_SHARP_CORNER","MAX_LINE_DISTANCE","LINE_DISTANCE_BUFFER_BITS","LineBucket","LineLayoutArray","lineSortKey","patternBucketFeature","cap","miterLimit","roundLimit","addLine","distance","scaledDistance","totalDistance","clipStart","clipEnd","isPolygon","currentVertex","sharpCornerOffset","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","leftX","leftY","rightX","rightY","up","linesofar","line-cap","line-join","line-miter-limit","line-round-limit","line-sort-key","line-opacity","line-color","line-translate","line-translate-anchor","line-width","line-offset","line-blur","line-dasharray","line-gradient","lineFloorwidthProperty","LineStyleLayer","_updateGradient","gradient","gradientTexture","lineBucket","getLineWidth","halfWidth","lineOffset","newRings","zero","newRing","aToB","bToC","offsetLine","multiLine","polygonIntersectsBufferedMultiLine","lineWidth","lineGapWidth","symbolLayoutAttributes","dynamicLayoutAttributes","collisionVertexAttributes","collisionBoxLayout","collisionCircleLayout","toLocaleUpperCase","toLocaleLowerCase","transformText","verticalizedCharacterMap","#","$","&","(",")",",",".",":",";","=","?","@","[","\\","]","`","{","|","}","~","¢","£","¥","¦","¬","¯","–","—","‘","’","“","”","…","‧","₩","、","。","〈","〉","《","》","「","」","『","』","【","】","〔","〕","〖","〗","!","(",")",",","-",".",":",";","<",">","?","[","]","_","{","|","}","⦅","⦆","。","「","」","WritingMode","horizontal","vertical","horizontalOnly","getAnchorAlignment","anchor","horizontalAlign","verticalAlign","Anchor","SIZE_PACK_FACTOR","getSizeData","tileZoom","minZoom","maxZoom","evaluateSizeForFeature","sizeData","uSizeT","uSize","evaluateSizeForZoom","layoutSize","minSize","shaderOpacityAttributes","ox","oy","tx","ty","sizeVertex","addDynamicAttributes","dynamicLayoutVertexArray","SymbolBuffers","SymbolLayoutArray","SymbolDynamicLayoutArray","opacityVertexArray","SymbolOpacityArray","placedSymbolArray","dynamicIndexBuffer","dynamicLayoutVertexBuffer","opacityVertexBuffer","itemSize","CollisionBuffers","LayoutArray","IndexArray","collisionVertexArray","CollisionVertexArray","collisionVertexBuffer","SymbolBucket","collisionBoxArray","pixelRatio","hasPaintOverrides","unevaluatedLayoutValues","textSizeData","iconSizeData","sortFeaturesByKey","zOrderByViewportY","sortFeaturesByY","writingModes","wm","sourceID","createArrays","SymbolStyleLayer","icon","collisionBox","CollisionBoxLayoutArray","collisionCircle","CollisionCircleLayoutArray","glyphOffsetArray","lineVertexArray","symbolInstances","calculateGlyphDependencies","stack","textAlongLine","allowVerticalPlacement","doesAllowVerticalWritingMode","verticalChar","charAt","textFont","textField","iconImage","hasText","hasIcon","symbolSortKey","icons","iconDependencies","stacks","glyphDependencies","resolvedTokens","getValueAndResolveTokens","symbolFeature","sectionFont","sectionStack","leftIndex","rightIndex","mergedFeatures","mergedIndex","mergeFromRight","leftKey","rightKey","geom","mergeFromLeft","getKey","onRight","mergeLines","addToLineVertexArray","sumForwardLength","sumBackwardLength","vertex","addSymbols","arrays","quads","alongLine","labelAnchor","glyphOffsetArrayStart","addSymbol","symbol","tr","bl","tex","glyphOffset","currentSectionIndex","populatePaintArrayForSection","sectionIndex","lastSection","_addCollisionDebugVertex","addCollisionDebugVertices","boxAnchorPoint","symbolInstance","isCircle","indexArray$1","addDebugCollisionBoxes","startIndex","endIndex","box","generateCollisionDebugBuffers","_deserializeCollisionBoxesForSymbol","textStartIndex","textEndIndex","verticalTextStartIndex","verticalTextEndIndex","iconStartIndex","iconEndIndex","collisionArrays","textBox","textFeatureIndex","textCircles","verticalTextBox","verticalTextFeatureIndex","iconBox","iconFeatureIndex","deserializeCollisionBoxes","hasTextData","hasIconData","hasCollisionBoxData","hasCollisionCircleData","addIndicesForPlacedTextSymbol","placedTextSymbolIndex","placedSymbol","vertexIndex","getSortedSymbolIndexes","sortedAngle","symbolInstanceIndexes","rotatedYs","featureIndexes","aIndex","bIndex","sortFeatures","featureSortOrder","placedIcon","MAX_GLYPHS","symbol-placement","symbol-spacing","symbol-avoid-edges","symbol-sort-key","symbol-z-order","icon-allow-overlap","icon-ignore-placement","icon-optional","icon-rotation-alignment","icon-size","icon-text-fit","icon-text-fit-padding","icon-image","icon-rotate","icon-padding","icon-keep-upright","icon-offset","icon-anchor","icon-pitch-alignment","text-pitch-alignment","text-rotation-alignment","text-field","text-font","text-size","text-max-width","text-line-height","text-letter-spacing","text-justify","text-radial-offset","text-variable-anchor","text-anchor","text-max-angle","text-writing-mode","text-rotate","text-padding","text-keep-upright","text-transform","text-offset","text-allow-overlap","text-ignore-placement","text-optional","icon-translate","icon-translate-anchor","runtimeType","getOverride","o","hasOverride","text-translate","text-translate-anchor","FormatSectionOverride","defaultValue","deduped","_setPaintOverrides","unevaluated","resolveTokens","hasPaintOverride","overriden","override","styleExpression","_interpolationType","propertyName","hasOverrides","checkSections","checkExpression","background-color","background-pattern","background-opacity","BackgroundStyleLayer","raster-opacity","raster-hue-rotate","raster-brightness-min","raster-brightness-max","raster-saturation","raster-contrast","raster-resampling","raster-fade-duration","RasterStyleLayer","CustomStyleLayer","implementation","renderingMode","prerender","onAdd","painter","onRemove","subclasses","circle","heatmap","hillshade","fill","fill-extrusion","fillExtrusion","background","raster","createStyleLayer","potpack","boxes","maxWidth","spaces","space","ImagePosition","paddedRect","displaySize","ImageAtlas","iconPositions","haveRenderCallbacks","bins","addImages","bin","images","hasRenderCallback","patchUpdatedImages","imageManager","dispatchRenderCallbacks","updatedImages","patchUpdatedImage","position","Texture","renderStyleImage","userImage","render","useMipmap","pixelStoreUnpackFlipY","pixelStoreUnpack","pixelStoreUnpackPremultiplyAlpha","premultiply","HTMLImageElement","HTMLCanvasElement","HTMLVideoElement","texSubImage2D","isSizePowerOfTwo","generateMipmap","minFilter","LINEAR_MIPMAP_NEAREST","LINEAR","texParameteri","TEXTURE_MAG_FILTER","TEXTURE_MIN_FILTER","TEXTURE_WRAP_S","TEXTURE_WRAP_T","ImageManager","callbackDispatchedThisFrame","loaded","requestors","atlasImage","setLoaded","_notify","addImage","updateImage","oldImage","removeImage","listImages","getImages","hasAllDependencies","sdf","getPixelSize","getPattern","pattern","_updatePatternAtlas","atlasTexture","CLAMP_TO_EDGE","dst","beginFrame","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","Pbf","buf","Varint","Fixed64","Bytes","Fixed32","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","ieee754","readVarintRemainder","bytesPerSequence","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","readGlyph","bitmap","metrics","advance","glyph","TinySDF","INF","fontSize","cutoff","fontFamily","fontWeight","textBaseline","fillStyle","gridOuter","gridInner","middle","userAgent","edt","edt1d","draw","clearRect","fillText","imgData","alphaChannel","GlyphManager","requestManager","localIdeographFontFamily","entries","setURL","getGlyphs","entry","requests","_tinySDF","range","loadGlyphRange","_doesCharSupportLocalGlyph","cb","family","tinySDF","fontstack","urlTemplate","Protobuf","parseGlyphPBF","LightPositionProperty","azimuthal","polar","intensity","Light","lightOptions","_transitionable","setLight","_transitioning","getLight","LineAtlas","nextRow","bytes","getDash","dasharray","addDash","stretch","oddLength","row","partIndex","distLeft","distRight","signedDistance","distMiddle","distEdge","REPEAT","ThrottledInvoker","_callback","_triggered","MessageChannel","_channel","port2","onmessage","trigger","port1","postMessage","Actor","callbacks","tasks","taskQueue","cancelCallbacks","invoker","process","receive","targetMapId","substring","hasCallback","sourceMapId","task","completed","done","getWorkerSource","Dispatcher","workerPool","actors","currentActor","workers","acquire","getMercCoords","resolution","broadcast","release","LngLatBounds","sw","ne","setSouthWest","setNorthEast","_ne","LngLat","lng","lat","_sw","sw2","ne2","getCenter","getSouthWest","getNorthEast","getNorthWest","getWest","getNorth","getSouthEast","getEast","getSouth","toBounds","latAccuracy","lngAccuracy","lon","circumferenceAtEquator","circumferenceAtLatitude","latitude","mercatorXfromLng","mercatorYfromLat","mercatorZfromAltitude","altitude","latFromMercatorY","MercatorCoordinate","fromLngLat","lngLatLike","lngLat","toLngLat","toAltitude","meterInMercatorCoordinateUnits","CanonicalTileID","calculateKey","urls","scheme","quadkey","mask","getQuadkey","getTilePoint","coord","tilesAtZoom","UnwrappedTileID","OverscaledTileID","overscaledZ","vector_layers","vectorLayers","vectorLayerIds","scaledTo","targetZ","zDifference","isChildOf","children","sourceMaxZoom","isLessThan","wrapped","unwrapTo","overscaleFactor","toUnwrapped","TileBounds","validateBounds","contains","tileID","worldSize","level","VectorTileSource","eventedParent","reparseOverscaled","_loaded","_options","_collectResourceTiming","collectResourceTiming","load","dataType","_tileJSONRequest","loadTileJSON","_requestManager","tileBounds","_getMapId","sourceDataType","hasTile","loadTile","tile","showCollisionBoxes","resourceTiming","_refreshExpiredTiles","setExpiryData","loadVectorData","reloadCallback","state","abortTile","unloadTile","unloadVectorData","RasterTileSource","roundZoom","getTileTexture","extTextureFilterAnisotropic","texParameterf","TEXTURE_MAX_ANISOTROPY_EXT","extTextureFilterAnisotropicMax","saveTileTexture","DEMData","encoding","stride","pixels","unpack","_unpackTerrarium","_unpackMapbox","_idx","getPixels","backfillBorder","borderTile","xMin","xMax","yMin","yMax","RasterDEMTileSource","dem","needsHillshadePrepare","rawImageData","neighboringTiles","_getNeighboringTiles","pxw","nxw","backfilled","demTexture","fbo","GeoJSONSource","_removed","_data","_resourceTiming","attribution","workerOptions","geojsonVtOptions","tolerance","generateId","superclusterOptions","clusterMaxZoom","clusterRadius","_updateWorkerData","setData","getClusterExpansionZoom","clusterId","getClusterChildren","getClusterLeaves","limit","abandoned","ImageSource","newCoordinates","successCallback","_finishLoading","setCoordinates","cornerCoords","dMax","getCoordinatesCenterTileID","tileCoords","_boundsArray","RasterBoundsArray","boundsBuffer","prepare","rasterBoundsAttributes","boundsSegments","buckets","VideoSource","video","muted","onloadstart","host","crossOrigin","getVideo","loop","triggerRepaint","play","pause","seek","seconds","seekableRange","seekable","currentTime","readyState","paused","CanvasSource","animate","getElementById","_hasInvalidDimensions","_playing","getCanvas","sourceTypes","vector","raster-dem","rasterDem","geojson","getPixelPosMatrix","mat4","calculatePosMatrix","queryRenderedFeatures","sourceCache","styleLayers","has3DLayer","queryIncludes3DLayer","maxPitchScaleFactor","tilesIn","sortTilesIn","renderedFeatureLayers","tileIn","wrappedTileID","queryResults","_state","cameraQueryGeometry","wrappedIDLayerMap","wrappedID","wrappedIDLayers","layerID","tileFeatures","wrappedIDFeatures","resultFeatures","tileFeature","mergeRenderedFeatureLayers","featureWrapper","getFeatureState","idA","idB","DictionaryCoder","strings","_stringToNumber","_numberToString","encode","decode","Feature","vectorTileFeature","_vectorTileFeature","_z","_x","_y","SourceFeatureState","stateChanges","deletedStates","updateState","featureId","newState","ft","removeFeatureState","getState","changes","reconciledState","featureDeletions","initializeTileState","setFeatureState","coalesceChanges","featuresChanged","layerStates","FeatureIndex","featureIndexArray","grid3D","getBounds","topDownFeatureComparator","loadVTLayers","vtLayers","vt","VectorTile","rawTileData","sourceLayerCoder","sourceFeatureState","featureFilter","queryPadding","matching","cameraBounds","matching3D","bx1","by1","bx2","by2","boxX1","boxY1","boxX2","boxY2","polygonIntersectsBox","previousIndex","featureGeometry","this$1","loadMatchingFeature","filterLayerIDs","layerIDs","bucketLayerIDs","arraysIntersect","sourceLayerName","intersectionZ","geojsonFeature","GeoJSONFeature","layerResult","lookupSymbolFeatures","symbolFeatureIndexes","symbolFeatureIndex","hasLayer","uses","expirationTime","hasSymbolBuckets","expiredRequestCount","registerFadeDuration","fadeEndTime","timeAdded","wasRequested","justReloaded","hasData","latestFeatureIndex","latestRawTileData","getLayer","lId","deserializeBucket","imageAtlas","glyphAtlasImage","imageAtlasTexture","glyphAtlasTexture","unloadDEMData","getBucket","ALPHA","querySourceFeatures","_geojsonTileLayer","clearMask","maskedBoundsBuffer","maskedIndexBuffer","setMask","0","maskedBoundsArray","maskArray","maskCoord","vertexExtent","tlVertex","brVertex","patternsLoaded","parsedCC","isExpired","delta","getExpiryTimeout","sourceLayerId","sourceLayerStates","holdingForFade","symbolFadeHoldUntil","symbolFadeFinished","clearFadeHold","setHoldDuration","TileCache","reset","removedData","timeout","clearTimeout","order","expiryTimeout","dataWrapper","_getAndRemoveByKey","getAndRemove","dataIndex","setMaxSize","IndexBuffer","dynamicDraw","createBuffer","unbindVAO","bindElementBuffer","bufferData","ELEMENT_ARRAY_BUFFER","DYNAMIC_DRAW","STATIC_DRAW","bufferSubData","deleteBuffer","AttributeType","VertexBuffer","bindVertexBuffer","ARRAY_BUFFER","enableAttributes","program","attribIndex","enableVertexAttribArray","setVertexAttribPointers","vertexAttribPointer","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","Program","useProgram","ActiveTextureUnit","TEXTURE0","activeTexture","Viewport","drawingBufferWidth","drawingBufferHeight","viewport","BindFramebuffer","bindFramebuffer","FRAMEBUFFER","BindRenderbuffer","bindRenderbuffer","RENDERBUFFER","BindTexture","BindVertexBuffer","bindBuffer","BindElementBuffer","BindVertexArrayOES","vao","extVertexArrayObject","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","Framebuffer","framebuffer","createFramebuffer","colorAttachment","depthAttachment","renderbuffer","deleteRenderbuffer","deleteFramebuffer","DepthMode","ReadOnly","ReadWrite","disabled","StencilMode","fail","depthFail","ColorMode","blendFunction","Replace","unblended","alphaBlended","CullFaceMode","mode","backCCW","Context","getExtension","stencilTest","depthTest","blend","cullFaceSide","getParameter","MAX_TEXTURE_MAX_ANISOTROPY_EXT","extTextureHalfFloat","createRenderbuffer","storageFormat","rbo","renderbufferStorage","COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","setCullFace","cullFaceMode","setDepthMode","depthMode","setStencilMode","stencilMode","setColorMode","colorMode","SourceCache","_sourceLoaded","_paused","reload","_sourceErrored","_source","createSource","_tiles","_cache","_unloadTile","_timers","_cacheTimers","_maxTileCacheSize","_coveredTiles","getSource","resume","shouldReload","_shouldReloadOnResume","_loadTile","_abortTile","getIds","compareKeyZoom","getRenderableIds","symbolLayer","_isIdRenderable","a_","b_","rotatedA","rotatedB","hasRenderableParent","parentTile","findLoadedParent","_reloadTile","_tileLoaded","previousState","refreshedUponExpiration","_setTileReloadTimer","_backfillDEM","renderables","borderId","getTileByID","fillBorder","getTile","getZoom","scaleZoom","_retainLoadedChildren","idealTiles","maxCoveringZoom","retain","topmostLoadedID","parentID","minCoveringZoom","updateCacheSize","approxTilesInView","viewDependentMaxSize","handleWrapJump","worldDifference","_prevLng","wrapDelta","idealTileIDs","center","used","getVisibleUnwrappedCoordinates","unwrapped","coveringTiles","maxOverzooming","maxUnderzooming","_updateRetainedTiles","isRasterType","parentsForFading","fadingTiles","_addTile","retainedId","keysDifference","_fadeDuration","_removeTile","releaseSymbolFadeTiles","checked","missingTiles","childCoord","childTile","parentWasRequested","parentId","clearTiles","pointQueryGeometry","tileResults","cameraPointQueryGeometry","getCameraQueryGeometry","pointCoordinate","tileSpaceBounds","tileSpaceQueryGeometry","tileSpaceCameraQueryGeometry","getVisibleCoordinates","posMatrix","workerUrl","WorkerPool","active","workerCount","WebWorker","globalWorkerPool","availableLogicalProcessors","deref","refProperties","derefLayers","operations","setStyle","addLayer","removeLayer","setFilter","addSource","removeSource","setGeoJSONSourceData","setLayerZoomRange","setLayerProperty","setCenter","setZoom","setBearing","setPitch","setSprite","setGlyphs","sourceId","after","commands","command","sourcesRemoved","updateSource","canUpdateGeoJSON","before","isEqual","diffLayerPropertyChanges","pluckId","indexById","group","diffStyles","pitch","removeOrAddSourceCommands","diffSources","beforeLayers","beforeLayer","afterLayer","insertBeforeLayerId","beforeOrder","afterOrder","beforeIndex","afterIndex","tracker","clean","diffLayers","cellSize","boxCells","circleCells","xCellCount","yCellCount","circleKeys","boxKeys","circles","xScale","yScale","boxUid","circleUid","getLabelPlaneMatrix","pitchWithMap","rotateWithMap","labelPlaneMatrix","getGlCoordMatrix","glCoordMatrix","matrix","xyTransformMat4","signedDistanceFromCamera","isVisible","anchorPos","clippingBuffer","updateLineLabels","isText","keepUpright","partiallyEvaluatedSize","symbolSize","placedSymbols","aspectRatio","useVertical","hideGlyphs","perspectiveRatio","pitchScaledFontSize","tileAnchorPoint","projectionCache","placeUnflipped","placeGlyphsAlongLine","notEnoughRoom","needsFlipping","placeFirstAndLastGlyph","fontScale","flip","returnTileDistance","glyphEndIndex","lineEndIndex","firstGlyphOffset","lastGlyphOffset","firstPlacedGlyph","placeGlyphAlongLine","lastPlacedGlyph","requiresOrientationChange","firstPoint","lastPoint","placedGlyphs","firstAndLastGlyph","orientationChange","glyphIndex","tileVertexIndex","tileSegmentEnd","projectedVertex","projectTruncatedLineSegment","singleGlyph","previousTilePoint","currentTilePoint","previousProjectedPoint","minimumLength","projectionMatrix","projectedUnitVertex","projectedUnitSegment","anchorSegment","combinedOffsetX","initialIndex","distanceToPrev","currentSegmentDistance","absOffsetX","projection","previousLineVertexIndex","segmentInterpolationT","prevToCurrent","tileDistance","prevTileDistance","lastSegmentViewportDistance","keysLength","_insertBoxCell","insertCircle","_insertCircleCell","_query","hitTest","predicate","queryArgs","_queryCircle","_queryCellCircle","hitTestCircle","boxCell","circleCell","_circleAndRectCollide","_circlesCollide","_convertToXCellCoord","_convertToYCellCoord","r1","r2","bothRadii","circleX","circleY","halfRectWidth","distX","halfRectHeight","distY","hiddenGlyphAttributes","CollisionIndex","ignoredGrid","pitchfactor","_pitch","screenRightBoundary","screenBottomBoundary","gridRightBoundary","gridBottomBoundary","markCollisionCircleUsed","collisionCircles","placeCollisionBox","allowOverlap","textPixelRatio","collisionGroupPredicate","projectedPoint","projectAndGetPerspectiveRatio","tileToViewport","tlX","tlY","brX","brY","isInsideGrid","offscreen","isOffscreen","approximateTileDistance","lastSegmentAngle","cameraToAnchorDistance","incidenceStretch","lastSegmentTile","placeCollisionCircles","showCollisionCircles","placedCollisionCircles","projectedAnchor","projectAnchor","tileUnitAnchorPoint","collisionDetected","inGrid","entirelyOffscreen","firstTileDistance","lastTileDistance","cameraDistance","tileUnitRadius","boxSignedDistanceFromAnchor","nextBoxDistanceToAnchor","collisionBoxArrayIndex","queryRenderedSymbols","viewportQueryGeometry","gridPoint","seenFeatures","featureKey","bucketInstanceId","intersectionTests","insertCollisionBox","ignorePlacement","collisionGroupID","insertCollisionCircles","seed","remainder","h1","h1b","c1","c2","k1","murmur3","baselineOffset","evaluateRadialOffset","radialOffset","hypotenuse","pixelValue","OpacityState","prevState","increment","placed","skipFade","opacity","JointOpacityState","placedText","JointPlacement","RetainedQueryData","CollisionGroups","crossSourceCollisions","maxGroupID","collisionGroups","calculateVariableLayoutOffset","shiftX","shiftY","ID","nextGroupID","Placement","prevPlacement","collisionIndex","placements","opacities","variableOffsets","stale","commitTime","retainedQueryData","placedOrientations","updateCollisionVertices","notUsed","placeLayerTile","seenCrossTileIDs","symbolBucket","bucketFeatureIndex","textLabelPlaneMatrix","iconLabelPlaneMatrix","placeLayerBucket","attemptAnchorPlacement","collisionGroup","textAllowOverlap","orientation","prevAnchor","placedGlyphBoxes","rotatedOffset","shiftVariableCollisionBox","markUsedJustification","markUsedOrientation","partiallyEvaluatedTextSize","textOptional","iconOptional","iconAllowOverlap","alwaysShowText","alwaysShowIcon","placeSymbol","placeText","placeIcon","placedVertical","placedGlyphCircles","placedIconBoxes","updatePreviousOrientationIfNotPlaced","isPlaced","previousOrientation","prevPlacedOrientation","placeTextForPlacementModes","placeHorizontalFn","placeVerticalFn","anchors","prevOffsets","unshift","placeBoxForVariableAnchors","collisionTextBox","placedBox","placementAttempts","wasPlaced","prevOrientation","prevOffset","placeBox","placedFeature","iconWithoutText","textWithoutIcon","symbolIndexes","symbolIndex","placedAnchor","autoIndex","justifications","getAnchorJustification","commit","placementChanged","prevOpacities","prevOrientations","jointPlacement","prevOpacity","jointOpacity","lastPlacementChangeTime","updateLayerOpacities","updateBucketOpacities","duplicateOpacityState","variablePlacement","defaultOpacityState","isDuplicate","opacityState","packedOpacity","packOpacity","opacityEntryCount","symbolHidden","verticalHidden","horizontalHidden","variableOffset","symbolFadeChange","hasTransitions","stillRecent","setStale","shift25","shift24","shift17","shift16","shift9","shift8","shift1","targetBit","opacityBits","LayerPlacement","_currentTileIndex","_seenCrossTileIDs","continuePlacement","placement","shouldPausePlacement","PauseablePlacement","forceFullPlacement","_currentPlacementIndex","_forceFullPlacement","_showCollisionBoxes","_done","isDone","layerTiles","startTime","elapsedTime","placementZoom","_inProgressLayer","roundingFactor","TileLayerIndex","indexedSymbolInstances","getScaledCoordinates","childTileID","findMatches","newTileID","zoomCrossTileIDs","indexedInstances","scaledSymbolCoord","thisTileSymbol","CrossTileIDs","maxCrossTileID","generate","CrossTileSymbolLayerIndex","indexes","usedCrossTileIDs","zoomIndexes","newZoomIndex","addBucket","crossTileIDs","removeBucketCrossTileIDs","childIndex","parentIndex","symbolInstance$1","removedBucket","removeStaleBuckets","currentIDs","tilesChanged","tileKey","CrossTileSymbolIndex","layerIndexes","maxBucketInstanceId","bucketsInCurrentPlacement","layerIndex","symbolBucketsChanged","currentBucketIDs","pruneUnusedLayers","usedLayers","usedLayerMap","usedLayer","_emitValidationErrors","supportedDiffOperations","diffOperations","ignoredDiffOperations","glyphManager","lineAtlas","crossTileSymbolIndex","_layers","_order","sourceCaches","_resetUpdates","_rtlTextPluginCallback","registerForPluginAvailability","completionCallback","_validateLayer","loadURL","_request","_load","loadJSON","stylesheet","_spriteRequest","baseURL","jsonRequest","maybeComplete","imageRequest","imageData","loadSprite","_serializeLayers","_updatedSources","serializedLayers","_checkLoaded","changed","_changed","updatedIds","_updatedLayers","removedIds","_removedLayers","_updateWorkerLayers","action","_reloadSource","_clearSource","_updatedPaintProps","setState","nextState","unimplementedOps","isSourceLoaded","layerObject","validateCustomStyleLayer","_layerOrderChanged","removed","_updateLayer","moveLayer","newIndex","getFilter","_flattenAndSortRenderedFeatures","sourceResults","isLayer3D","features3D","layerFeatures","topmost3D","includedSources","renderedSymbols","bucketQueryData","queryData","bucketSymbols","layerSymbols","sortedA","layerName","dataTiles","dataID","addSourceType","SourceType","getSourceType","setSourceType","workerSourceURL","_update","_remove","rtlTextPluginEvented","_updateSources","_generateCollisionBoxes","_updatePlacement","placementCommitted","layerBucketsChanged","pauseablePlacement","_releaseSymbolFadeTiles","getResource","prelude","compile","backgroundPattern","clippingMask","heatmapTexture","debug","fillOutline","fillOutlinePattern","fillPattern","fillExtrusionPattern","hillshadePrepare","lineGradient","linePattern","lineSDF","symbolIcon","symbolSDF","fragmentSource","vertexSource","re","fragmentPragmas","operation","precision","attrType","unpackType","VertexArrayObject","boundProgram","boundLayoutVertexBuffer","boundPaintVertexBuffers","boundIndexBuffer","boundVertexOffset","boundDynamicVertexBuffer","paintVertexBuffers","dynamicVertexBuffer","dynamicVertexBuffer2","paintBuffersDiffer","isFreshBindRequired","boundDynamicVertexBuffer2","freshBind","numPrevAttributes","numNextAttributes","numAttributes","createVertexArrayOES","currentNumAttributes","disableVertexAttribArray","vertexBuffer","vertexBuffer$1","deleteVertexArrayOES","configuration","fixedUniforms","showOverdrawInspector","createProgram","fragmentShader","createShader","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","vertexShader","VERTEX_SHADER","bindAttribLocation","linkProgram","getProgramParameter","ACTIVE_ATTRIBUTES","uniformLocations","attribute","getActiveAttrib","getAttribLocation","numUniforms","ACTIVE_UNIFORMS","getActiveUniform","getUniformLocation","patternUniformValues","tileRatio","numTiles","tileSizeAtNearestZoom","pixelX","pixelY","u_image","u_texsize","u_scale","u_fade","u_pixel_coord_upper","u_pixel_coord_lower","drawMode","uniformValues","currentProperties","dynamicLayoutBuffer","dynamicLayoutBuffer2","primitiveSize","LINES","TRIANGLES","LINE_STRIP","drawElements","UNSIGNED_SHORT","fillExtrusionUniformValues","shouldUseVerticalGradient","_lp","lightPos","lightMat","mat3","vec3","lightColor","u_matrix","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","collisionUniforms","u_pixels_to_tile_units","u_overscale_factor","collisionUniformValues","debugUniformValues","u_color","clippingMaskUniformValues","heatmapUniformValues","u_intensity","heatmapTextureUniformValues","textureUnit","colorRampUnit","u_color_ramp","hillshadeUniformValues","shadow","highlight","accent","moving","u_latrange","getTileLatRange","u_light","u_shadow","u_highlight","u_accent","hillshadeUniformPrepareValues","u_dimension","u_zoom","u_maxzoom","lineUniformValues","calculateMatrix","u_ratio","u_units_to_pixels","lineGradientUniformValues","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","texSize","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_texture","symbolSDFUniformValues","isHalo","u_gamma_scale","u_is_halo","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","renderableTiles","sortedRenderables","childArray","computeTileMasks","rootTile","lowerBound","diffZ","maskTileId","drawCollisionDebugGeometry","drawCircles","colorModeForRenderPass","identityMat4","calculateVariableRenderShift","renderTextSize","updateVariableAnchors","tileScale","skipOrientation","tileAnchor","symbolProjection","ONE_EM","tilePixelRatio","shiftedAnchor","updateVerticalLabels","drawLayerSymbols","rotationAlignment","pitchAlignment","depthModeForSublayer","tileRenderState","programConfiguration","isSDF","sdfIcons","atlasInterpolation","iconScaled","iconsNeedLinear","iconTransformed","rotating","zooming","NEAREST","uLabelPlaneMatrix","uglCoordMatrix","hasHalo","segmentState","drawSymbolElements","drawFillTiles","isOutline","programName","tileMatrix","stencilModeForClipping","drawExtrusionTiles","renderHillshade","rasterBoundsBuffer","quadTriangleIndexBuffer","rasterBoundsSegments","prepareHillshade","textureStride","pixelData","TEXTURE1","renderTexture","getFadeValues","sinceTile","sinceParent","idealZ","coveringZoomLevel","fadeIn","childOpacity","drawDebugTile","debugBuffer","tileBorderIndexBuffer","debugSegments","tileRawData","tileByteLength","tileSizeKb","scaleRatio","baseline","len2","strokes","simplexFont","createTextVertices","debugTextArray","PosArray","debugTextIndices","debugTextBuffer","posAttributes","debugTextIndexBuffer","debugTextSegment","onePixel","translations","translation"," ","\"","'","1","2","3","4","5","6","7","8","9","A","B","C","D","F","G","H","I","J","K","L","M","O","P","Q","R","S","T","U","V","W","X","Y","Z","renderPass","drawCollisionDebug","strokeWidth","strokeOpacity","segmentsRenderStates","segmentsState","bindTextureToFramebuffer","HALF_FLOAT_OES","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","viewportBuffer","viewportSegments","renderTextureToMap","programId","firstTile","prevProgram","programChanged","opaquePassEnabledForLayer","LEQUAL","depthRangeFor3D","stencilModeFor3D","tileIDs","minTileZ","textureFilter","isPatternMissing","tileExtentBuffer","tileExtentSegments","setCustomLayerDefaults","customLayerMatrix","setBaseState","Painter","_tileTextures","setup","numSublayers","depthEpsilon","depthRboNeedsClear","emptyProgramConfiguration","edge","scanSpans","e0","ymin","ymax","scanLine","m0","d0","d1","scanTriangle","bc","ca","depthRbo","tileExtentArray","debugArray","rasterBoundsArray","viewportArray","tileLineStripIndices","LineStripIndexArray","quadTriangleIndices","stencilClearMode","nextStencilID","currentStencilSource","_renderTileClippingMasks","_tileClippingMaskIDs","REPLACE","NOTEQUAL","EQUAL","_showOverdrawInspector","CONSTANT_COLOR","currentLayer","opaquePassCutoff","coordsAscending","coordsDescending","coordsDescendingSymbol","visibleTiles","updateTileMasks","renderLayer","showTileBoundaries","setupOffscreenDepthRenderbuffer","DEPTH_COMPONENT16","inViewportPixelUnitsUnits","sinA","cosA","translatedMatrix","textures","shaders","Transform","renderWorldCopies","maxValidLatitude","_renderWorldCopies","_minZoom","_maxZoom","setMaxBounds","_center","_fov","_unmodified","_posMatrixCache","_alignedPosMatrixCache","latRange","_calcMatrices","centerPoint","rotationMatrix","mat2","a3","fov","_zoom","zoomScale","zoomFraction","_constrain","utl","utr","ubl","ubr","w0","w1","actualZ","centerCoord","zoomedBounds","tileCover","unmodified","lnglat","unproject","setLocationAtPoint","loc","locationCoordinate","newCenter","coordinateLocation","locationPoint","coordinatePoint","pointLocation","coord0","coord1","pixelMatrixInverse","z0","z1","pixelMatrix","getMaxBounds","lngRange","unwrappedTileID","aligned","posMatrixKey","unwrappedX","alignedProjMatrix","projMatrix","mercatorMatrix","_constraining","sy","sx","h2","w2","halfFov","groundAngle","topHalfSurfaceDistance","farZ","nearZ","fovy","aspect","xShift","yShift","angleCos","angleSin","alignedM","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","det","getCameraPoint","yOffset","Hash","time","pending","timerId","later","_updateHash","_updateHashUnthrottled","addTo","_map","_onHashChange","getHashString","mapFeedback","getBearing","getPitch","hash","jumpTo","history","replaceState","SecurityError","MapMouseEvent","originalEvent","getCanvasContainer","_defaultPrevented","defaultPrevented","MapTouchEvent","lngLats","curr","MapWheelEvent","ScrollZoomHandler","_el","_delta","_defaultZoomRate","_wheelZoomRate","setZoomRate","zoomRate","setWheelZoomRate","wheelZoomRate","isEnabled","_enabled","isActive","_active","isZooming","_zooming","_aroundCenter","around","onWheel","deltaMode","WheelEvent","DOM_DELTA_LINE","deltaY","timeDelta","_lastWheelEventTime","_type","_lastValue","_timeout","_onTimeout","shiftKey","_lastWheelEvent","_start","initialEvent","_frameId","_cancelRenderFrame","_finishTimeout","_around","_aroundPoint","_requestRenderFrame","_onScrollFrame","_targetZoom","_startZoom","_easing","_smoothOutEasing","targetZoom","startZoom","easing","finished","_ease","_prevEase","speed","BoxZoomHandler","_container","getContainer","_clickTolerance","clickTolerance","onMouseDown","_onMouseMove","_onKeyDown","_onMouseUp","_startPos","_lastPos","_box","p0","classList","_fireEvent","_finish","fitScreenCoordinates","linear","keyCode","inertiaEasing","DragRotateHandler","element","_button","_bearingSnap","bearingSnap","_pitchWithRotate","pitchWithRotate","_unbind","_deactivate","touchEvent","_startTime","_eventButton","_onBlur","_inertia","_prevPos","_lastMoveEvent","_onDragFrame","bearingDiff","pitchDiff","inertia","_drainInertiaBuffer","_normalizeBearing","click","_inertialRotate","mapBearing","resetNorth","noMoveStart","previous","flingDiff","flingDuration","rotateTo","DragPanHandler","_onMove","onTouchStart","passive","_onTouchEnd","_mouseDownPos","_inertialPan","flingOffset","velocity","panBy","KeyboardHandler","easeOut","altKey","metaKey","zoomDir","bearingDir","pitchDir","xDir","yDir","easeOptions","delayEndEvents","easeTo","DoubleClickZoomHandler","_tapped","newTap","firstTap","_tappedPoint","onTouchEnd","onTouchCancel","_resetTapped","onDblClick","_onZoomEnd","zoomTo","TouchZoomRotateHandler","disableRotation","_rotationDisabled","enableRotation","onStart","_startVec","_startAround","_gestureIntent","_onEnd","_getTouchEventData","scalingSignificantly","_lastTouchEvent","_onTouchFrame","gestureIntent","_startScale","_startBearing","aroundPoint","startScale","snapToNorth","lastScale","firstScale","scaleOffset","scaleDuration","targetScale","handlers","scrollZoom","boxZoom","dragRotate","dragPan","keyboard","doubleClickZoom","touchZoomRotate","Camera","_moving","panTo","zoomIn","zoomOut","resetNorthPitch","cameraForBounds","_cameraForBoxAndBearing","p0world","p1world","p0rotated","p1rotated","upperRight","lowerLeft","scaleX","scaleY","paddingOffsetX","paddingOffsetY","offsetAtFinalZoom","fitBounds","_fitInternal","calculatedOptions","flyTo","zoomChanged","bearingChanged","pitchChanged","defaultEasing","startBearing","startPitch","pointAtOffset","locationAtOffset","_normalizeCenter","finalScale","_rotating","_pitching","_prepareEase","_easeEndTimeoutID","speedup","_fireMoveEvents","_afterEase","wasZooming","wasRotating","wasPitching","coercedOptions","curve","rho","u1","wMax","rho2","sinh","cosh","r0","screenSpeed","maxDuration","isEasing","_easeFrameId","_onEaseFrame","_onEaseEnd","onEaseEnd","_easeStart","_easeOptions","_renderFrameCallback","currentBearing","diff","AttributionControl","getDefaultPosition","compact","_innerContainer","_updateAttributions","_updateEditLink","_updateData","_updateCompact","editLink","_editLink","querySelector","styleOwner","styleId","paramString","acc","_hash","rel","attributions","customAttribution","owner","attribHTML","attrib","_attribHTML","innerHTML","offsetWidth","LogoControl","setAttribute","display","_updateLogo","_logoRequired","mapbox_logo","containerChildren","TaskQueue","_queue","_id","_cleared","_currentlyRunning","running","run","defaultOptions","interactive","attributionControl","preserveDrawingBuffer","trackResize","refreshExpiredTiles","maxTileCacheSize","Map","_interactive","_failIfMajorPerformanceCaveat","_preserveDrawingBuffer","_antialias","_trackResize","_crossSourceCollisions","_crossFadingFactor","_renderTaskQueue","_controls","_mapId","HTMLElement","maxBounds","_setupContainer","_setupPainter","_onWindowOnline","_onWindowResize","contextMenuEvent","mouseDown","mapEvent","bindHandlers","fitBoundsOptions","_localIdeographFontFamily","addControl","logoPosition","control","controlElement","positionContainer","_controlPositions","insertBefore","firstChild","removeControl","ci","_containerDimensions","_resizeCanvas","setMinZoom","getMinZoom","setMaxZoom","getRenderWorldCopies","setRenderWorldCopies","getMaxZoom","isMoving","isRotating","delegatedListener","mousein","delegates","_delegatedListeners","listeners","_diffStyle","_updateStyle","_updateDiff","getStyle","isStyleLoaded","areTilesLoaded","existingImage","hasImage","loadImage","beforeId","_canvasContainer","_canvas","clientWidth","clientHeight","_detectMissingCSS","getComputedStyle","_missingCSSCanary","getPropertyValue","canvasContainer","_contextLost","_contextRestored","controlContainer","_controlContainer","positionName","testSupport","_frame","_styleDirty","_sourcesDirty","updateStyle","_render","crossFading","factor","_placementDirty","_repaint","loseContext","_showTileBoundaries","repaint","_vertices","_setCacheLimits","checkThreshold","setCacheLimits","showCompass","showZoom","visualizePitch","NavigationControl","_zoomInButton","_createButton","_zoomOutButton","_compass","_compassArrow","priorPos","_updateZoomButtons","_rotateCompassArrow","_handler","ariaLabel","title","anchorTranslate","top-left","top-right","bottom-left","bottom-right","applyAnchorClass","prefix","supportsGeolocation","Marker","legacyOptions","_anchor","_color","_draggable","draggable","_element","_offset","_defaultMarker","svg","createNS","setAttributeNS","markerLarge","page1","rx","ry","ellipse","bgPath","borderPath","maki","circleContainer","circle1","circle2","_popup","setDraggable","_onMapClick","_addDragHandler","_onUp","getLngLat","_lngLat","setLngLat","_pos","getElement","setPopup","popup","linearOffset","markerHeight","targetElement","togglePopup","getPopup","isOpen","smartWrap","getOffset","setOffset","_positionDelta","pointerEvents","shouldBeDraggable","isDraggable","positionOptions","enableHighAccuracy","maximumAge","trackUserLocation","showUserLocation","GeolocateControl","_setupUI","permissions","geolocation","_geolocationWatchID","clearWatch","_userLocationDotMarker","_onSuccess","_lastKnownPosition","_watchState","_geolocateButton","_updateMarker","_updateCamera","_dotElement","longitude","accuracy","geolocateSource","_onError","_clearWatch","_timeoutId","_setup","watchPosition","getCurrentPosition","ScaleControl","updateScale","latlng1","latlng2","lat1","lat2","maxMeters","maxFeet","setScale","maxDistance","pow10","multiplier","getDecimalRoundNum","ratio","setUnit","FullscreenControl","_fullscreen","_fullscreenchange","_className","_checkFullscreenSupport","_changeIcon","fullscreenEnabled","mozFullScreenEnabled","msFullscreenEnabled","webkitFullscreenEnabled","_fullscreenButton","_updateTitle","_onClickFullscreen","_isFullscreen","fullscreenElement","mozFullScreenElement","webkitFullscreenElement","msFullscreenElement","toggle","exitFullscreen","mozCancelFullScreen","msExitFullscreen","webkitCancelFullScreen","requestFullscreen","mozRequestFullScreen","msRequestFullscreen","webkitRequestFullscreen","closeButton","closeOnClick","Popup","_onClickClose","_trackPointer","_content","trackPointer","setText","setDOMContent","createTextNode","setHTML","html","frag","createDocumentFragment","temp","getMaxWidth","setMaxWidth","htmlNode","_createContent","_closeButton","cursor","hasPosition","_tip","normalizeOffset","cornerOffset","convertedOffset","anchorComponents","offsetHeight","offsetedPos","baseApiUrl","count","maxParallelImageRequests","numRequests","clearStorage","promise","clearTileCache"],"mappings":"iRAiBA,SAASA,EAAYC,GACjB,SAcyB,oBAAXC,QAA8C,oBA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